use super::*;
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),
];
pub(super) const DEFAULT_MODEL: &str = "default (the command's own choice)";
pub(super) const OTHER_MODEL: &str = "another model, by its full name...";
#[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>,
}
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 {
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;
if !self.agent_is_beside() {
self.show_output = false;
}
self.check_account();
}
}
pub(super) fn check_account(&mut self) {
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));
});
}
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(),
KeyCode::Enter if alt => self.agent.type_char('\n'),
KeyCode::Enter if self.agent.account == Account::SignedOut && self.agent.input.trim().is_empty() => {
self.sign(false);
}
KeyCode::Enter => self.ask_agent(),
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()));
}
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),
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),
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)),
_ => {}
}
}
pub fn set_agents(&mut self, config: Option<&str>) {
let (agents, first, problem) = agent::load_specs(config);
self.stop_every_agent();
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);
}
}
pub(super) fn spec(&self) -> &AgentSpec {
&self.agents[self.agent_index]
}
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;
}
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()));
}
}
}
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);
}
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;
}
}
pub(super) fn fit_agent_title(&mut self, cells: usize) {
let tabs: usize = self.agent_tab_labels().iter().map(|label| label.chars().count()).sum();
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;
}
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()
}
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)),
}
}
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);
}
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);
}
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", ..) => {
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)),
},
Some(_) => {
let name = chosen.unwrap_or_default();
let name = name.split_whitespace().next().unwrap_or_default();
self.agent.set_input(&format!("/{name} "));
}
None => self.agent.set_input(&format!("/{typed}")),
}
}
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}"));
}
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())
})
}
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,
};
height.saturating_sub(3).max(1)
}
pub(super) fn agent_is_beside(&self) -> bool {
self.layout(self.size.0, self.size.1).agent_side > 0
}
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)
}
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);
let size = self.agent_size();
*(if beside { &mut self.agent_cols } else { &mut self.agent_rows }) = Some(size);
}
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) });
}
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);
}
}
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);
}
pub(super) fn sessions_dir(&self) -> PathBuf {
agent::sessions_dir(&self.home(), self.tree.root())
}
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");
self.agent_snapshot = None;
self.agent_changes.clear();
self.show_agent = true;
self.focus = Focus::Agent;
}
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");
}
}
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 {
""
};
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(),
}
}
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();
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();
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;
};
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
),
),
}
}
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;
self.agent_run = 0;
self.agent.say(Who::Note, why);
self.agent_finished();
}
}
pub(super) fn handle_agent(&mut self, run: u64, line: Option<String>) {
if run != self.agent_run {
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) {
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
}
None => {
let status = self.agent_child.take().and_then(|mut child| child.wait().ok());
let unfinished = self.agent.running;
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();
}
}
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)"));
}
}
}
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();
}
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),
}
}
pub(super) fn run_in_terminal(&mut self, words: &[String], what: &str) -> std::io::Result<()> {
use std::sync::atomic::Ordering;
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);
self.screen = Screen::with_theme(self.screen.theme);
self.tree.refresh();
self.reload_changed();
self.refresh_git();
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(())
}
}