curd-editor 0.27.1

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
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
//! The panels of the assistants (Claude, Cursor and others): each with a
//! conversation of its own.

use super::*;

/// The `/` commands of the Claude panel: the name, what it does, and the
/// key in the panel that does the same (none for the ones handled by
/// name).
pub(super) const SLASH: [(&str, &str, KeyCode, KeyModifiers); 16] = [
    ("agent", "choose which assistant answers: Claude or another", KeyCode::Null, NONE),
    ("login", "sign in to its account, in the terminal", KeyCode::Null, NONE),
    ("logout", "sign out of its account", KeyCode::Null, NONE),
    ("account", "say who is signed in", KeyCode::Null, NONE),
    ("model", "choose the model that answers", KeyCode::Null, NONE),
    ("attach", "attach a file to the next question (also @)", KeyCode::Null, NONE),
    ("detach", "take the attached files off again", KeyCode::Null, NONE),
    ("new", "start a new conversation", KeyCode::Char('n'), CTRL),
    ("resume", "carry on an earlier conversation", KeyCode::Char('r'), CTRL),
    ("mode", "what it may do: change files, read, run commands", KeyCode::Char('m'), ALT),
    ("undo", "put the files it changed back as they were", KeyCode::Char('u'), ALT),
    ("changes", "open the files it changed", KeyCode::Char('o'), ALT),
    ("copy", "copy the last answer", KeyCode::Char('c'), ALT),
    ("bigger", "make this panel as big as it goes, and back", KeyCode::Char('z'), ALT),
    ("help", "every command of the editor", KeyCode::F(1), NONE),
    ("hide", "hide this panel", KeyCode::Char('i'), ALT),
];

/// The first and last lines of the list of models; the assistant's own
/// come between them.
pub(super) const DEFAULT_MODEL: &str = "default (the command's own choice)";
pub(super) const OTHER_MODEL: &str = "another model, by its full name...";

/// An assistant's panel while another one is in front: its conversation
/// and everything else that is its own. Each assistant is like an
/// extension of its own: its panel keeps what was said, what is being
/// typed, its model and what it may do, and it goes on working in the
/// background when another panel is looked at.
#[derive(Default)]
pub(super) struct Parked {
    pub(super) panel: Panel,
    pub(super) child: Option<std::process::Child>,
    pub(super) run: u64,
    pub(super) snapshot: Option<Snapshot>,
    pub(super) changes: Vec<Change>,
}

/// A new, empty panel for the assistant `spec`.
pub(super) fn panel_for(spec: &AgentSpec) -> Panel {
    let mut panel = Panel::new();
    panel.name = spec.name.clone();
    panel.fixed_mode = !spec.has_modes();
    panel
}

impl Workspace {
    // ---- The Claude panel ---------------------------------------------

    /// Alt+I: shows the panel and puts the keys there; pressed again while
    /// the keys are there, hides it.
    pub(super) fn toggle_agent(&mut self) {
        if self.show_agent && self.focus == Focus::Agent {
            self.show_agent = false;
            self.leave_agent();
        } else {
            self.show_agent = true;
            self.focus = Focus::Agent;
            // Under the text there is room for one panel.
            if !self.agent_is_beside() {
                self.show_output = false;
            }
            self.check_account();
        }
    }

    /// Finds out, for the assistant in front, whether its program is
    /// there and whether an account is signed in, which is what its
    /// panel starts with. Its own command is asked, in the background.
    pub(super) fn check_account(&mut self) {
        // Once is enough, until something is done about it. With another
        // command put in its place (CURD_AGENT) there is nothing to ask.
        let Some(events) = self.events.clone().filter(|_| self.agent_setting.is_none()) else {
            return;
        };
        if self.agent.account != Account::Unknown {
            return;
        }
        let spec = self.spec();
        let path = std::env::var("PATH").unwrap_or_default();
        if !agent::is_installed(&spec.command[0], &path) {
            self.agent.account = Account::Missing(spec.install.clone());
            return;
        }
        let Some((program, arguments)) = spec.status.split_first() else {
            return;
        };
        let (program, arguments) = (program.clone(), arguments.to_vec());
        let (index, root) = (self.agent_index, self.tree.root().to_path_buf());
        std::thread::spawn(move || {
            let output = std::process::Command::new(&program)
                .args(&arguments)
                .current_dir(root)
                .stdin(std::process::Stdio::null())
                .output();
            let (printed, succeeded) = match output {
                Ok(output) => (
                    String::from_utf8_lossy(&[output.stdout, output.stderr].concat()).into_owned(),
                    output.status.success(),
                ),
                Err(_) => (String::new(), false),
            };
            let _ = events.send(AppEvent::Account(index, printed, succeeded));
        });
    }

    /// Puts the keys back in the text, or the tree when no file is open.
    pub(super) fn leave_agent(&mut self) {
        self.focus = if self.has_files() { Focus::Editor } else { Focus::Tree };
    }

    pub(super) fn agent_key(&mut self, key: KeyEvent) {
        let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
        let alt = key.modifiers.contains(KeyModifiers::ALT);
        match key.code {
            KeyCode::Esc if self.agent.running => self.stop_agent("Stopped"),
            KeyCode::Esc => self.leave_agent(),
            // Alt+Enter starts a new line in the question.
            KeyCode::Enter if alt => self.agent.type_char('\n'),
            // Signing in comes first: with no account, Enter on an empty
            // question is "sign in".
            KeyCode::Enter if self.agent.account == Account::SignedOut && self.agent.input.trim().is_empty() => {
                self.sign(false);
            }
            KeyCode::Enter => self.ask_agent(),
            // `/` at the start of the question lists the commands, and `@`
            // anywhere picks a file to attach.
            KeyCode::Char('/') if !ctrl && !alt && self.agent.input.is_empty() => self.list_slash(),
            KeyCode::Char('@') if !ctrl && !alt => {
                self.picker = Picker::Attach;
                self.finder = Some(Finder::new(self.tree.root()));
            }
            // An assistant whose own settings decide has nothing to switch.
            KeyCode::Char('m') if alt && !self.agent.running && !self.agent.fixed_mode => {
                self.agent.next_mode();
            }
            KeyCode::Char('n') if ctrl && !self.agent.running => self.agent.clear(),
            KeyCode::Char('z') if alt => self.zoom_agent(),
            KeyCode::Char('u') if alt && !self.agent.running => self.undo_agent(),
            KeyCode::Char('o') if alt => self.open_agent_changes(),
            KeyCode::Char('c') if alt => self.copy_answer(),
            KeyCode::Char('r') if (ctrl || alt) && !self.agent.running => self.list_sessions(),
            KeyCode::Up if alt => self.grow_agent(true),
            KeyCode::Down if alt => self.grow_agent(false),
            // Each assistant has a panel of its own, side by side.
            KeyCode::Left if alt => self.next_agent(-1),
            KeyCode::Right if alt => self.next_agent(1),
            KeyCode::Char(c) if !ctrl && !alt => self.agent.type_char(c),
            KeyCode::Backspace => self.agent.backspace(),
            KeyCode::Delete => self.agent.delete(),
            KeyCode::Left => self.agent.move_cursor(-1),
            KeyCode::Right => self.agent.move_cursor(1),
            KeyCode::Home => self.agent.move_cursor(isize::MIN),
            KeyCode::End => self.agent.move_cursor(isize::MAX),
            // The questions asked before.
            KeyCode::Up => self.agent.recall(-1),
            KeyCode::Down => self.agent.recall(1),
            KeyCode::PageUp => self.agent.scroll_by(self.agent_rows() as isize),
            KeyCode::PageDown => self.agent.scroll_by(-(self.agent_rows() as isize)),
            _ => {}
        }
    }

    /// Sets up the assistants from `config`, the contents of agents.json
    /// (if there is one).
    pub fn set_agents(&mut self, config: Option<&str>) {
        let (agents, first, problem) = agent::load_specs(config);
        self.stop_every_agent();
        // Each gets a panel of its own; the one to start with is in front.
        self.parked = agents.iter().map(|spec| Parked { panel: panel_for(spec), ..Parked::default() }).collect();
        self.agents = agents;
        self.agent_index = first.min(self.agents.len().saturating_sub(1));
        let front = std::mem::take(&mut self.parked[self.agent_index]);
        self.agent = front.panel;
        (self.agent_run, self.agent_snapshot, self.agent_changes) = (0, None, Vec::new());
        if let Some(problem) = problem {
            self.agent.say(Who::Note, problem);
        }
    }

    /// The assistant whose panel is in front.
    pub(super) fn spec(&self) -> &AgentSpec {
        &self.agents[self.agent_index]
    }

    /// Brings the panel of assistant `index` to the front. The one that
    /// was in front keeps everything as it is, and goes on with what it
    /// was doing.
    pub(super) fn use_agent(&mut self, index: usize) {
        let index = index.min(self.agents.len().saturating_sub(1));
        if index == self.agent_index {
            return;
        }
        let next = std::mem::take(&mut self.parked[index]);
        self.parked[self.agent_index] = Parked {
            panel: std::mem::replace(&mut self.agent, next.panel),
            child: std::mem::replace(&mut self.agent_child, next.child),
            run: std::mem::replace(&mut self.agent_run, next.run),
            snapshot: std::mem::replace(&mut self.agent_snapshot, next.snapshot),
            changes: std::mem::replace(&mut self.agent_changes, next.changes),
        };
        self.agent_index = index;
    }

    /// Shows the panel of assistant `index` and puts the keys there, and
    /// keeps it as the one to start with next time.
    pub(super) fn open_agent(&mut self, index: usize) {
        self.use_agent(index);
        self.show_agent = true;
        self.focus = Focus::Agent;
        if !self.agent_is_beside() {
            self.show_output = false;
        }
        self.check_account();
        if let Some(file) = &self.agents_file {
            let before = std::fs::read_to_string(file).ok();
            let saved = agent::with_default(before.as_deref(), &self.agent.name).is_some_and(|text| {
                let folder = file.parent().unwrap_or(Path::new("."));
                std::fs::create_dir_all(folder).and_then(|()| std::fs::write(file, text)).is_ok()
            });
            if !saved {
                self.agent.say(Who::Note, format!("Could not keep that choice in {}", file.display()));
            }
        }
    }

    /// Alt+Left and Alt+Right in a panel: the panel of the assistant
    /// before, or after, this one.
    pub(super) fn next_agent(&mut self, step: isize) {
        let count = self.agents.len() as isize;
        self.open_agent((self.agent_index as isize + step).rem_euclid(count) as usize);
    }

    /// Stops every assistant that is working, in front or not.
    pub(super) fn stop_every_agent(&mut self) {
        self.stop_agent("Stopped");
        for parked in &mut self.parked {
            if let Some(mut child) = parked.child.take() {
                let _ = child.kill();
                let _ = child.wait();
            }
            parked.panel.running = false;
        }
    }

    /// Makes room in the title of a panel `cells` wide for the tabs of the
    /// assistants, where the whole of it would not leave any.
    pub(super) fn fit_agent_title(&mut self, cells: usize) {
        let tabs: usize = self.agent_tab_labels().iter().map(|label| label.chars().count()).sum();
        // The longest a title gets, with its reminder of a key.
        let title = " may change files and run commands (Alt+M)".len() + self.agent.name.chars().count() + 3;
        self.agent.brief = self.agents.len() > 1 && title + tabs > cells;
    }

    /// The tabs for the title of the panel, one per assistant, and how
    /// wide they are together: a mark on the ones that are working.
    pub(super) fn agent_tab_labels(&self) -> Vec<String> {
        (0..self.agents.len())
            .map(|index| {
                let running = match index == self.agent_index {
                    true => self.agent.running,
                    false => self.parked[index].panel.running,
                };
                format!(" {}{} ", self.agents[index].name, if running { " *" } else { "" })
            })
            .collect()
    }

    /// `/login` and `/logout`: runs the assistant's own command for it,
    /// with the whole terminal to itself. It opens the sign-in page of
    /// whoever makes the assistant; the editor sees none of it.
    pub(super) fn sign(&mut self, out: bool) {
        let spec = self.spec();
        let (words, what) = match out {
            true => (spec.logout.clone(), format!("Signing out of {}", spec.name)),
            false => (spec.login.clone(), format!("Signing in to {}", spec.name)),
        };
        match words.is_empty() {
            true => self.agent.say(Who::Note, "No command for that is set for this assistant"),
            false => self.terminal_job = Some((words, what)),
        }
    }

    /// `/account`: asks the assistant's command who is signed in.
    pub(super) fn show_account(&mut self) {
        let words = self.spec().status.clone();
        let Some((program, arguments)) = words.split_first() else {
            return self.agent.say(Who::Note, "No command for that is set for this assistant");
        };
        let output = std::process::Command::new(program)
            .args(arguments)
            .current_dir(self.tree.root())
            .stdin(std::process::Stdio::null())
            .output();
        let said = match output {
            Ok(output) => agent::account(&String::from_utf8_lossy(&[output.stdout, output.stderr].concat())),
            Err(_) => format!("Could not run {program}: is it installed?"),
        };
        self.agent.say(Who::Note, said);
    }

    /// `/` in the panel: lists its commands, and the user's own that the
    /// `claude` command knows.
    pub(super) fn list_slash(&mut self) {
        let mut lines: Vec<String> = SLASH
            .iter()
            .map(|(name, what, ..)| format!("{name:<10}{what}"))
            .collect();
        let own = agent::own_commands(&self.home(), self.tree.root());
        lines.extend(own.iter().map(|name| format!("{name:<10} (yours: sent to claude)")));
        self.pick(Picker::Slash, lines);
    }

    /// Carries out line `index` of the `/` list; `typed` is what was
    /// typed after the `/`, for when no line was picked.
    pub(super) fn run_slash(&mut self, index: Option<usize>, chosen: Option<String>, typed: &str) {
        match index {
            Some(index) if index < SLASH.len() => match SLASH[index] {
                ("agent", ..) => {
                    // Each with whether its program is there to run.
                    let path = std::env::var("PATH").unwrap_or_default();
                    let names = self
                        .agents
                        .iter()
                        .map(|spec| {
                            let there = match agent::is_installed(&spec.command[0], &path) {
                                true => "ready".to_string(),
                                false => format!("not installed: {}", spec.install),
                            };
                            format!("{:<12}{there}", spec.name)
                        })
                        .collect();
                    self.pick(Picker::Agent, names);
                }
                ("login", ..) => self.sign(false),
                ("logout", ..) => self.sign(true),
                ("account", ..) => self.show_account(),
                ("model", ..) => {
                    let mut models = vec![DEFAULT_MODEL.to_string()];
                    models.extend(self.spec().models.iter().cloned());
                    models.push(OTHER_MODEL.to_string());
                    self.pick(Picker::Model, models);
                }
                ("attach", ..) => {
                    self.picker = Picker::Attach;
                    self.finder = Some(Finder::new(self.tree.root()));
                }
                ("detach", ..) => self.agent.attached.clear(),
                (_, _, code, modifiers) => self.handle_key(KeyEvent::new(code, modifiers)),
            },
            // One of the user's own: it goes to claude as the question,
            // with room to say more after it.
            Some(_) => {
                let name = chosen.unwrap_or_default();
                let name = name.split_whitespace().next().unwrap_or_default();
                self.agent.set_input(&format!("/{name} "));
            }
            // Nothing by that name here: perhaps claude knows it.
            None => self.agent.set_input(&format!("/{typed}")),
        }
    }

    /// Sets the model from line `index` of the list of models.
    pub(super) fn choose_model(&mut self, index: usize) {
        let models = &self.spec().models;
        match index {
            0 => self.agent.model = None,
            other if other > models.len() => return self.pick(Picker::ModelName, Vec::new()),
            index => self.agent.model = Some(models[index - 1].clone()),
        }
        let model = self.agent.model.as_deref().unwrap_or("the default model");
        self.agent.say(Who::Note, format!("The next answers come from {model}"));
    }

    /// The user's home folder, where `claude` keeps its things.
    pub(super) fn home(&self) -> PathBuf {
        self.agent_home.clone().unwrap_or_else(|| {
            let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
            PathBuf::from(home.unwrap_or_default())
        })
    }

    /// Rows of the conversation on screen: one page for PageUp/PageDown.
    pub(super) fn agent_rows(&self) -> usize {
        let layout = self.layout(self.size.0, self.size.1);
        let height = match layout.agent_side {
            0 => layout.agent,
            _ => layout.pane_height + layout.output,
        };
        // Less its title, the row above the question, and the question.
        height.saturating_sub(3).max(1)
    }

    /// True when the panel stands beside the text, not under it.
    pub(super) fn agent_is_beside(&self) -> bool {
        self.layout(self.size.0, self.size.1).agent_side > 0
    }

    /// How big the panel is: its columns when it stands beside the text,
    /// its rows when it lies under it.
    pub(super) fn agent_size(&self) -> usize {
        let layout = self.layout(self.size.0, self.size.1);
        layout.agent_side.saturating_sub(1).max(layout.agent)
    }

    /// Makes the panel `size` big (see `agent_size`), as far as the screen
    /// allows.
    pub(super) fn resize_agent(&mut self, size: usize) {
        let beside = self.agent_is_beside();
        let wanted = if beside { &mut self.agent_cols } else { &mut self.agent_rows };
        *wanted = Some(size);
        // Keep what the screen made of it, not what was asked for.
        let size = self.agent_size();
        *(if beside { &mut self.agent_cols } else { &mut self.agent_rows }) = Some(size);
    }

    /// Alt+Up and Alt+Down: a little bigger, a little smaller.
    pub(super) fn grow_agent(&mut self, bigger: bool) {
        let step = if self.agent_is_beside() { 6 } else { 2 };
        let size = self.agent_size();
        self.resize_agent(if bigger { size + step } else { size.saturating_sub(step) });
    }

    /// Alt+Z: makes the panel as big as it can be, or its usual size again.
    pub(super) fn zoom_agent(&mut self) {
        let before = self.agent_size();
        self.resize_agent(usize::MAX);
        if self.agent_size() == before {
            (self.agent_rows, self.agent_cols) = (None, None);
        }
    }

    /// Ctrl+R: lists the earlier conversations about this project, to
    /// carry one on.
    pub(super) fn list_sessions(&mut self) {
        self.agent_sessions = agent::list_sessions(&self.sessions_dir());
        if self.agent_sessions.is_empty() {
            self.agent.say(Who::Note, "No earlier conversations about this project");
            return;
        }
        let now = std::time::SystemTime::now();
        let lines = self
            .agent_sessions
            .iter()
            .map(|session| format!("{:>3}  {}", agent::age(session.modified, now), session.title))
            .collect();
        self.pick(Picker::Sessions, lines);
    }

    /// Where the `claude` command keeps this project's conversations.
    pub(super) fn sessions_dir(&self) -> PathBuf {
        agent::sessions_dir(&self.home(), self.tree.root())
    }

    /// Shows conversation `index` of the list again, to carry it on.
    pub(super) fn resume_session(&mut self, index: usize) {
        let Some(session) = self.agent_sessions.get(index) else {
            return;
        };
        let entries = agent::load_session(&self.sessions_dir(), &session.id);
        self.agent.resume(session.id.clone(), entries);
        self.agent.say(Who::Note, "Carrying on this conversation");
        // What Claude changed back then is not ours to undo now.
        self.agent_snapshot = None;
        self.agent_changes.clear();
        self.show_agent = true;
        self.focus = Focus::Agent;
    }

    /// Alt+C: copies the last answer.
    pub(super) fn copy_answer(&mut self) {
        if let Some(answer) = self.agent.last_answer() {
            self.clipboard = answer.to_string();
            self.clipboard_out = Some(self.clipboard.clone());
            self.agent.say(Who::Note, "Copied the last answer");
        }
    }

    /// What the editor is showing, for Claude to know what "this" means.
    pub(super) fn agent_context(&self) -> String {
        match self.editors.get(self.active) {
            Some(editor) if editor.abs_path.is_some() => {
                let unsaved = if editor.document.dirty {
                    " It has changes that are not saved to disk yet."
                } else {
                    ""
                };
                // Selected text is what the question is most likely about.
                let selected = match editor.selected_text() {
                    Some((first, last, text)) => {
                        let text: String = text.chars().take(MAX_SELECTION_CHARS).collect();
                        format!(
                            " The user has selected lines {} to {} of it:\n{text}",
                            first + 1,
                            last + 1
                        )
                    }
                    None => String::new(),
                };
                format!(
                    "The user is asking from inside the curd text editor. The file in front is {}, with the cursor on line {}.{unsaved}{selected}",
                    editor.abs_path.as_deref().unwrap_or_default(),
                    editor.cursor_line() + 1,
                )
            }
            _ => "The user is asking from inside the curd text editor.".into(),
        }
    }

    /// Enter in the panel: sends what was typed to the `claude` command.
    pub(super) fn ask_agent(&mut self) {
        if self.agent.running {
            return;
        }
        let Some(prompt) = self.agent.take_input() else {
            return;
        };
        let context = self.agent_context();
        // Attached files go along by name, for Claude to read.
        let attached = std::mem::take(&mut self.agent.attached);
        let sent = match attached.len() {
            0 => prompt.clone(),
            _ => format!(
                "{prompt}\n\nThe user attached these files (named from the project folder). Read them first: {}",
                attached.join(", ")
            ),
        };
        let model = self.agent.model.clone();
        // An assistant that does not say what its conversations are called
        // is asked to carry on its last one, once there has been a question.
        let asked_before = self.agent.entries.iter().any(|(who, _)| *who == Who::You);
        let session = match &self.agent.session {
            Some(session) => Some(session.as_str()),
            None if asked_before && self.spec().format == Format::Text => Some(""),
            None => None,
        };
        let request = Request {
            model: model.as_deref(),
            prompt: &sent,
            session,
            can_edit: self.agent.can_edit,
            can_run: self.agent.can_run,
            context: &context,
        };
        let (Some(words), Some(events)) =
            (self.spec().command_line(self.agent_setting.as_deref(), &request), &self.events)
        else {
            self.agent.say(Who::Note, "The Claude panel is turned off (CURD_AGENT=off)");
            return;
        };
        // Remember the files as they are, to tell what Claude changes.
        self.agent_changes.clear();
        self.agent_snapshot = (self.agent.can_edit || self.agent.fixed_mode).then(|| {
            Snapshot::take(self.tree.root(), &finder::project_files(self.tree.root()))
        });
        self.next_run += 1;
        self.agent_run = self.next_run;
        let run = self.agent_run;
        let events = events.clone();
        let forward = move |line| {
            let _ = events.send(AppEvent::Agent(run, line));
        };
        self.agent.say(Who::You, prompt);
        if !attached.is_empty() {
            self.agent.say(Who::Note, format!("With {}", attached.join(", ")));
        }
        let selection = self.editors.get(self.active).and_then(Editor::selected_text);
        if let Some((first, last, _)) = selection {
            self.agent.say(Who::Note, format!("With the selected lines {} to {}", first + 1, last + 1));
        }
        if std::env::var_os("ANTHROPIC_API_KEY").is_some() {
            self.agent.say(Who::Note, "ANTHROPIC_API_KEY is set, so claude bills that key and not your subscription");
        }
        if self.editors.iter().any(|editor| editor.document.dirty) {
            self.agent.say(Who::Note, "Unsaved changes are not on disk, so Claude does not see them");
        }
        match agent::start(&words, self.tree.root(), forward) {
            Ok(child) => {
                self.agent_child = Some(child);
                self.agent.start();
            }
            Err(_) => self.agent.say(
                Who::Note,
                format!(
                    "Could not run {}. To install {}: {}. Then type /login here to sign in.",
                    words[0],
                    self.spec().name,
                    self.spec().install
                ),
            ),
        }
    }

    /// Stops the `claude` command if it is working, noting `why`.
    pub(super) fn stop_agent(&mut self, why: &str) {
        if let Some(mut child) = self.agent_child.take() {
            let _ = child.kill();
            let _ = child.wait();
        }
        if self.agent.running {
            self.agent.running = false;
            // Whatever it still prints belongs to no run now.
            self.agent_run = 0;
            self.agent.say(Who::Note, why);
            self.agent_finished();
        }
    }

    /// A line from the `claude` command, or its end.
    pub(super) fn handle_agent(&mut self, run: u64, line: Option<String>) {
        if run != self.agent_run {
            // From an assistant that works in the background: its panel
            // is brought to the front for as long as it takes to deal
            // with it.
            let Some(index) = self.parked.iter().position(|parked| parked.run == run && run != 0) else {
                return;
            };
            let front = self.agent_index;
            self.use_agent(index);
            self.handle_agent(run, line);
            return self.use_agent(front);
        }
        let ended = match line {
            Some(line) => {
                let mut ended = false;
                for update in self.spec().parse(&line) {
                    // Files are named from the project folder, not the
                    // top of the disk.
                    let update = match update {
                        agent::Update::Step(step) => {
                            agent::Update::Step(agent::shorten(&step, self.tree.root()))
                        }
                        other => other,
                    };
                    ended |= self.agent.apply(update);
                }
                ended
            }
            // It exited. Without an answer, the last thing it printed
            // says why.
            None => {
                let status = self.agent_child.take().and_then(|mut child| child.wait().ok());
                let unfinished = self.agent.running;
                // A command that answers in plain text says it is done by
                // ending well.
                let plain = self.spec().format == Format::Text;
                if unfinished && plain && status.is_some_and(|status| status.success()) {
                    self.agent.apply(agent::Update::Done);
                } else if unfinished {
                    self.agent.running = false;
                    self.agent.say(
                        Who::Note,
                        "It stopped without an answer. If you are not signed in, type /login.",
                    );
                }
                unfinished
            }
        };
        if ended && !self.agent.running {
            self.agent_finished();
        }
    }

    /// After an answer: Claude may have changed files.
    pub(super) fn agent_finished(&mut self) {
        self.tree.refresh();
        self.reload_changed();
        self.refresh_git();
        if let Some(snapshot) = &self.agent_snapshot {
            self.agent_changes = snapshot.changes(&finder::project_files(self.tree.root()));
            if !self.agent_changes.is_empty() {
                let summary = agent::describe(&self.agent_changes);
                self.agent.say(Who::Note, format!("{summary}  (Alt+O opens them, Alt+U undoes this)"));
            }
        }
    }

    /// Alt+U: puts every file Claude changed in its last answer back the
    /// way it was before.
    pub(super) fn undo_agent(&mut self) {
        let changes = std::mem::take(&mut self.agent_changes);
        let Some(snapshot) = self.agent_snapshot.take().filter(|_| !changes.is_empty()) else {
            self.agent.say(Who::Note, "Nothing of Claude's to undo");
            return;
        };
        let (restored, failed) = snapshot.restore(&changes);
        let files = if restored == 1 { "file" } else { "files" };
        self.agent.say(
            Who::Note,
            match failed {
                0 => format!("Put {restored} {files} back as before"),
                _ => format!("Put {restored} {files} back as before; {failed} could not be"),
            },
        );
        self.tree.refresh();
        self.reload_changed();
        self.refresh_git();
    }

    /// Alt+O: lists the files Claude changed in its last answer, to open.
    pub(super) fn open_agent_changes(&mut self) {
        let files: Vec<String> = self
            .agent_changes
            .iter()
            .filter(|change| change.kind != ChangeKind::Deleted)
            .map(|change| change.file.clone())
            .collect();
        match files.len() {
            0 => self.agent.say(Who::Note, "Claude changed no files in its last answer"),
            _ => self.pick(Picker::Files, files),
        }
    }

    /// Gives the whole terminal to the command `words` until it ends, and
    /// then takes it back: for signing in, and for programs that ask
    /// questions.
    pub(super) fn run_in_terminal(&mut self, words: &[String], what: &str) -> std::io::Result<()> {
        use std::sync::atomic::Ordering;
        // The thread that reads keys must have let go before it starts.
        self.input_paused.store(true, Ordering::Relaxed);
        std::thread::sleep(INPUT_WAIT + Duration::from_millis(50));
        Terminal::suspend()?;
        println!("{what}: {}\n", words.join(" "));
        let status = std::process::Command::new(&words[0])
            .args(&words[1..])
            .current_dir(self.tree.root())
            .status();
        let outcome = match status {
            Ok(status) if status.success() => "done".to_string(),
            Ok(status) => match status.code() {
                Some(code) => format!("failed (exit code {code})"),
                None => "stopped".to_string(),
            },
            Err(_) => format!("could not run {}: is it installed?", words[0]),
        };
        println!("\n{what}: {outcome}. Press Enter to go back to curd.");
        let _ = std::io::stdin().read_line(&mut String::new());
        Terminal::resume()?;
        self.input_paused.store(false, Ordering::Relaxed);
        // Everything is drawn again, and files may have changed meanwhile.
        self.screen = Screen::with_theme(self.screen.theme);
        self.tree.refresh();
        self.reload_changed();
        self.refresh_git();
        // Signing in or out may have changed who is signed in.
        self.agent.account = Account::Unknown;
        if self.show_agent {
            self.check_account();
        }
        let note = format!("{what}: {outcome}");
        match self.show_agent {
            true => self.agent.say(Who::Note, note),
            false => self.say(note),
        }
        Ok(())
    }
}