Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions crates/chat-cli/src/cli/chat/cli/changedir.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use std::path::PathBuf;

use clap::Args;
use crossterm::{
execute,
style,
};

use crate::cli::chat::{
ChatError,
ChatSession,
ChatState,
};
use crate::theme::StyledText;

#[derive(Debug, PartialEq, Args)]
/// Arguments for the changedir command.
pub struct ChangedirArgs {
/// The directory to switch to. Defaults to $HOME if not provided.
pub path: Option<PathBuf>,
}

impl ChangedirArgs {
pub async fn execute(self, session: &mut ChatSession) -> Result<ChatState, ChatError> {
let target = match self.path {
Some(p) => p,
None => dirs::home_dir().ok_or_else(|| ChatError::Custom("Could not determine home directory".into()))?,
};

let target = if target.is_relative() {
std::env::current_dir()
.map_err(|e| ChatError::Custom(e.to_string().into()))?
.join(&target)
} else {
target
};

std::env::set_current_dir(&target)
.map_err(|e| ChatError::Custom(format!("Failed to change directory: {e}").into()))?;

execute!(
session.stderr,
StyledText::success_fg(),
style::Print(format!("Working directory changed to: {}\n", target.display())),
style::Print("Run /code init to reinitialize code intelligence for this directory.\n"),
StyledText::reset(),
)?;

Ok(ChatState::PromptUser {
skip_printing_tools: true,
})
}
}
7 changes: 7 additions & 0 deletions crates/chat-cli/src/cli/chat/cli/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::theme::StyledText;
pub mod changelog;
pub mod changedir;
pub mod checkpoint;
pub mod clear;
pub mod compact;
Expand All @@ -23,6 +24,7 @@ pub mod tools;
pub mod usage;

use changelog::ChangelogArgs;
use changedir::ChangedirArgs;
use clap::Parser;
use clear::ClearArgs;
use compact::CompactArgs;
Expand Down Expand Up @@ -65,6 +67,9 @@ pub enum SlashCommand {
Quit,
/// Clear the conversation history
Clear(ClearArgs),
/// Change the working directory for this session
#[command(name = "changedir", alias = "cd")]
Changedir(ChangedirArgs),
/// Manage agents
#[command(subcommand)]
Agent(AgentSubcommand),
Expand Down Expand Up @@ -134,6 +139,7 @@ impl SlashCommand {
match self {
Self::Quit => Ok(ChatState::Exit),
Self::Clear(args) => args.execute(session).await,
Self::Changedir(args) => args.execute(session).await,
Self::Agent(subcommand) => subcommand.execute(os, session).await,
Self::Profile => {
use crossterm::{
Expand Down Expand Up @@ -203,6 +209,7 @@ impl SlashCommand {
match self {
Self::Quit => "quit",
Self::Clear(_) => "clear",
Self::Changedir(_) => "changedir",
Self::Agent(_) => "agent",
Self::Profile => "profile",
Self::Context(_) => "context",
Expand Down
7 changes: 7 additions & 0 deletions crates/chat-cli/src/cli/chat/line_tracker.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::time::SystemTime;

use serde::{
Deserialize,
Serialize,
Expand All @@ -19,6 +21,10 @@ pub struct FileLineTracker {
pub lines_removed_by_agent: usize,
/// Whether or not this is the first `fs_write` invocation
pub is_first_write: bool,
/// mtime of the file at the time it was last read by `fs_read`.
/// Used by `fs_write` to detect external modifications between read and write.
#[serde(skip)]
pub last_read_mtime: Option<SystemTime>,
}

impl Default for FileLineTracker {
Expand All @@ -30,6 +36,7 @@ impl Default for FileLineTracker {
lines_added_by_agent: 0,
lines_removed_by_agent: 0,
is_first_write: true,
last_read_mtime: None,
}
}
}
Expand Down
8 changes: 8 additions & 0 deletions crates/chat-cli/src/cli/chat/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,18 @@ pub struct ChatArgs {
/// Control line wrapping behavior (default: auto-detect)
#[arg(short = 'w', long, value_enum)]
pub wrap: Option<WrapMode>,
/// Set the working directory for this chat session
#[arg(long = "workdir", short = 'C', value_name = "PATH")]
pub workdir: Option<PathBuf>,
}

impl ChatArgs {
pub async fn execute(mut self, os: &mut Os) -> Result<ExitCode> {
if let Some(ref workdir) = self.workdir {
std::env::set_current_dir(workdir)
.map_err(|e| eyre::eyre!("Failed to set working directory '{}': {}", workdir.display(), e))?;
}

let mut input = self.input;

if self.no_interactive && input.is_none() {
Expand Down
59 changes: 44 additions & 15 deletions crates/chat-cli/src/cli/chat/tools/fs_read.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use std::fs::Metadata;
use std::io::Write;
Expand Down Expand Up @@ -43,6 +44,7 @@ use crate::cli::chat::{
CONTINUATION_LINE,
sanitize_unicode_tags,
};
use crate::cli::chat::line_tracker::FileLineTracker;
use crate::os::Os;
use crate::theme::StyledText;
use crate::util::paths;
Expand Down Expand Up @@ -266,7 +268,25 @@ impl FsRead {
}
}

pub async fn invoke(&self, os: &Os, updates: &mut impl Write) -> Result<InvokeOutput> {
pub async fn invoke(
&self,
os: &Os,
updates: &mut impl Write,
line_tracker: &mut HashMap<String, FileLineTracker>,
) -> Result<InvokeOutput> {
// Record mtime for each file-read operation so fs_write can detect
// external modifications between read and write.
for op in &self.operations {
if let Some(path) = op.file_path(os) {
if let Ok(meta) = std::fs::metadata(&path) {
if let Ok(mtime) = meta.modified() {
let key = path.to_string_lossy().to_string();
line_tracker.entry(key).or_default().last_read_mtime = Some(mtime);
}
}
}
}

if self.operations.len() == 1 {
// Single operation - return result directly
self.operations[0].invoke(os, updates).await
Expand Down Expand Up @@ -358,6 +378,15 @@ impl FsRead {
}

impl FsReadOperation {
/// Returns the resolved file path for Line operations (the only type that reads file content).
/// Used to record mtime for freshness checking in fs_write.
pub fn file_path(&self, os: &Os) -> Option<std::path::PathBuf> {
match self {
FsReadOperation::Line(fs_line) => Some(sanitize_path_tool_arg(os, &fs_line.path)),
_ => None,
}
}

pub async fn validate(&mut self, os: &Os) -> Result<()> {
match self {
FsReadOperation::Line(fs_line) => fs_line.validate(os).await,
Expand Down Expand Up @@ -943,7 +972,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -977,7 +1006,7 @@ mod tests {
assert!(
serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.is_err()
);
Expand Down Expand Up @@ -1010,7 +1039,7 @@ mod tests {
}]});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand All @@ -1029,7 +1058,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand All @@ -1055,7 +1084,7 @@ mod tests {
let v = serde_json::json!($value);
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1102,7 +1131,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1134,7 +1163,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1171,7 +1200,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand All @@ -1195,7 +1224,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1232,7 +1261,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1272,7 +1301,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1302,7 +1331,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand All @@ -1321,7 +1350,7 @@ mod tests {
});
let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();

Expand Down Expand Up @@ -1353,7 +1382,7 @@ mod tests {

let output = serde_json::from_value::<FsRead>(v)
.unwrap()
.invoke(&os, &mut stdout)
.invoke(&os, &mut stdout, &mut HashMap::new())
.await
.unwrap();
// All text operations should return combined text
Expand Down
Loading