Clean up session file optionality for --no-session (#3230)

This commit is contained in:
Jack Amadeo
2025-07-02 16:05:05 -04:00
committed by GitHub
parent 2e97621348
commit c77c1b364d
10 changed files with 179 additions and 213 deletions
+15 -3
View File
@@ -691,7 +691,11 @@ pub async fn cli() -> Result<()> {
})
.await;
setup_logging(
session.session_file().file_stem().and_then(|s| s.to_str()),
session
.session_file()
.as_ref()
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str()),
None,
)?;
@@ -831,7 +835,11 @@ pub async fn cli() -> Result<()> {
.await;
setup_logging(
session.session_file().file_stem().and_then(|s| s.to_str()),
session
.session_file()
.as_ref()
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str()),
None,
)?;
@@ -950,7 +958,11 @@ pub async fn cli() -> Result<()> {
})
.await;
setup_logging(
session.session_file().file_stem().and_then(|s| s.to_str()),
session
.session_file()
.as_ref()
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str()),
None,
)?;
if let Err(e) = session.interactive(None).await {
+1 -1
View File
@@ -15,7 +15,7 @@ impl BenchBaseSession for Session {
async fn headless(&mut self, message: String) -> anyhow::Result<()> {
self.headless(message).await
}
fn session_file(&self) -> PathBuf {
fn session_file(&self) -> Option<PathBuf> {
self.session_file()
}
fn message_history(&self) -> Vec<Message> {
+31 -38
View File
@@ -122,7 +122,7 @@ async fn offer_extension_debugging_help(
std::env::temp_dir().join(format!("goose_debug_extension_{}.jsonl", extension_name));
// Create the debugging session
let mut debug_session = Session::new(debug_agent, temp_session_file.clone(), false, None, true);
let mut debug_session = Session::new(debug_agent, Some(temp_session_file.clone()), false, None);
// Process the debugging request
println!("{}", style("Analyzing the extension failure...").yellow());
@@ -229,24 +229,16 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> Session {
}
// Handle session file resolution and resuming
let session_file: std::path::PathBuf = if session_config.no_session {
// Use a temporary path that won't be written to
#[cfg(unix)]
{
std::path::PathBuf::from("/dev/null")
}
#[cfg(windows)]
{
std::path::PathBuf::from("NUL")
}
let session_file: Option<std::path::PathBuf> = if session_config.no_session {
None
} else if session_config.resume {
if let Some(identifier) = session_config.identifier {
let session_file = match session::get_path(identifier) {
Ok(path) => path,
Err(e) => {
output::render_error(&format!("Invalid session identifier: {}", e));
process::exit(1);
}
Ok(path) => path,
};
if !session_file.exists() {
output::render_error(&format!(
@@ -256,11 +248,11 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> Session {
process::exit(1);
}
session_file
Some(session_file)
} else {
// Try to resume most recent session
match session::get_most_recent_session() {
Ok(file) => file,
Ok(file) => Some(file),
Err(_) => {
output::render_error("Cannot resume - no previous sessions found");
process::exit(1);
@@ -276,7 +268,7 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> Session {
// Just get the path - file will be created when needed
match session::get_path(id) {
Ok(path) => path,
Ok(path) => Some(path),
Err(e) => {
output::render_error(&format!("Failed to create session path: {}", e));
process::exit(1);
@@ -284,32 +276,34 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> Session {
}
};
if session_config.resume && !session_config.no_session {
// Read the session metadata
let metadata = session::read_metadata(&session_file).unwrap_or_else(|e| {
output::render_error(&format!("Failed to read session metadata: {}", e));
process::exit(1);
});
if session_config.resume {
if let Some(session_file) = session_file.as_ref() {
// Read the session metadata
let metadata = session::read_metadata(session_file).unwrap_or_else(|e| {
output::render_error(&format!("Failed to read session metadata: {}", e));
process::exit(1);
});
let current_workdir =
std::env::current_dir().expect("Failed to get current working directory");
if current_workdir != metadata.working_dir {
// Ask user if they want to change the working directory
let change_workdir = cliclack::confirm(format!("{} The original working directory of this session was set to {}. Your current directory is {}. Do you want to switch back to the original working directory?", style("WARNING:").yellow(), style(metadata.working_dir.display()).cyan(), style(current_workdir.display()).cyan()))
let current_workdir =
std::env::current_dir().expect("Failed to get current working directory");
if current_workdir != metadata.working_dir {
// Ask user if they want to change the working directory
let change_workdir = cliclack::confirm(format!("{} The original working directory of this session was set to {}. Your current directory is {}. Do you want to switch back to the original working directory?", style("WARNING:").yellow(), style(metadata.working_dir.display()).cyan(), style(current_workdir.display()).cyan()))
.initial_value(true)
.interact().expect("Failed to get user input");
if change_workdir {
if !metadata.working_dir.exists() {
output::render_error(&format!(
"Cannot switch to original working directory - {} no longer exists",
style(metadata.working_dir.display()).cyan()
));
} else if let Err(e) = std::env::set_current_dir(&metadata.working_dir) {
output::render_error(&format!(
"Failed to switch to original working directory: {}",
e
));
if change_workdir {
if !metadata.working_dir.exists() {
output::render_error(&format!(
"Cannot switch to original working directory - {} no longer exists",
style(metadata.working_dir.display()).cyan()
));
} else if let Err(e) = std::env::set_current_dir(&metadata.working_dir) {
output::render_error(&format!(
"Failed to switch to original working directory: {}",
e
));
}
}
}
}
@@ -373,7 +367,6 @@ pub async fn build_session(session_config: SessionBuilderConfig) -> Session {
session_file.clone(),
session_config.debug,
session_config.scheduled_job_id.clone(),
!session_config.no_session, // save_session is the inverse of no_session
);
// Add extensions if provided
+100 -82
View File
@@ -46,13 +46,12 @@ pub enum RunMode {
pub struct Session {
agent: Agent,
messages: Vec<Message>,
session_file: PathBuf,
session_file: Option<PathBuf>,
// Cache for completion data - using std::sync for thread safety without async
completion_cache: Arc<std::sync::RwLock<CompletionCache>>,
debug: bool, // New field for debug mode
run_mode: RunMode,
scheduled_job_id: Option<String>, // ID of the scheduled job that triggered this session
save_session: bool, // Whether to save session to file
}
// Cache structure for completion data
@@ -111,13 +110,12 @@ pub async fn classify_planner_response(
impl Session {
pub fn new(
agent: Agent,
session_file: PathBuf,
session_file: Option<PathBuf>,
debug: bool,
scheduled_job_id: Option<String>,
save_session: bool,
) -> Self {
let messages = if save_session {
match session::read_messages(&session_file) {
let messages = if let Some(session_file) = &session_file {
match session::read_messages(session_file) {
Ok(msgs) => msgs,
Err(e) => {
eprintln!("Warning: Failed to load message history: {}", e);
@@ -137,7 +135,6 @@ impl Session {
debug,
run_mode: RunMode::Normal,
scheduled_job_id,
save_session,
}
}
@@ -322,19 +319,21 @@ impl Session {
let provider = self.agent.provider().await?;
// Persist messages with provider for automatic description generation
session::persist_messages_with_schedule_id(
&self.session_file,
&self.messages,
Some(provider),
self.scheduled_job_id.clone(),
self.save_session,
)
.await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
Some(provider),
self.scheduled_job_id.clone(),
)
.await?;
}
// Track the current directory and last instruction in projects.json
let session_id = self
.session_file
.file_stem()
.as_ref()
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str())
.map(|s| s.to_string());
@@ -420,7 +419,8 @@ impl Session {
// Track the current directory and last instruction in projects.json
let session_id = self
.session_file
.file_stem()
.as_ref()
.and_then(|p| p.file_stem())
.and_then(|s| s.to_str())
.map(|s| s.to_string());
@@ -435,14 +435,15 @@ impl Session {
let provider = self.agent.provider().await?;
// Persist messages with provider for automatic description generation
session::persist_messages_with_schedule_id(
&self.session_file,
&self.messages,
Some(provider),
self.scheduled_job_id.clone(),
self.save_session,
)
.await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
Some(provider),
self.scheduled_job_id.clone(),
)
.await?;
}
output::show_thinking();
self.process_agent_response(true).await?;
@@ -624,14 +625,15 @@ impl Session {
self.messages = summarized_messages;
// Persist the summarized messages
session::persist_messages_with_schedule_id(
&self.session_file,
&self.messages,
Some(provider),
self.scheduled_job_id.clone(),
self.save_session,
)
.await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
Some(provider),
self.scheduled_job_id.clone(),
)
.await?;
}
output::hide_thinking();
println!(
@@ -655,8 +657,11 @@ impl Session {
}
println!(
"\nClosing session. Recorded to {}",
self.session_file.display()
"\nClosing session.{}",
self.session_file
.as_ref()
.map(|p| format!(" Recorded to {}", p.display()))
.unwrap_or_default()
);
Ok(())
}
@@ -744,19 +749,19 @@ impl Session {
}
async fn process_agent_response(&mut self, interactive: bool) -> Result<()> {
let session_id = session::Identifier::Path(self.session_file.clone());
let session_config = self.session_file.as_ref().map(|s| {
let session_id = session::Identifier::Path(s.clone());
SessionConfig {
id: session_id.clone(),
working_dir: std::env::current_dir()
.expect("failed to get current session working directory"),
schedule_id: self.scheduled_job_id.clone(),
execution_mode: None,
}
});
let mut stream = self
.agent
.reply(
&self.messages,
Some(SessionConfig {
id: session_id.clone(),
working_dir: std::env::current_dir()
.expect("failed to get current session working directory"),
schedule_id: self.scheduled_job_id.clone(),
execution_mode: None,
}),
)
.reply(&self.messages, session_config.clone())
.await?;
let mut progress_bars = output::McpSpinners::new();
@@ -803,7 +808,15 @@ impl Session {
Err(ToolError::ExecutionError("Tool call cancelled by user".to_string()))
));
self.messages.push(response_message);
session::persist_messages_with_schedule_id(&self.session_file, &self.messages, None, self.scheduled_job_id.clone(), self.save_session).await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
)
.await?;
}
drop(stream);
break;
@@ -885,13 +898,7 @@ impl Session {
.agent
.reply(
&self.messages,
Some(SessionConfig {
id: session_id.clone(),
working_dir: std::env::current_dir()
.expect("failed to get current session working directory"),
schedule_id: self.scheduled_job_id.clone(),
execution_mode: None,
}),
session_config.clone(),
)
.await?;
}
@@ -900,7 +907,15 @@ impl Session {
self.messages.push(message.clone());
// No need to update description on assistant messages
session::persist_messages_with_schedule_id(&self.session_file, &self.messages, None, self.scheduled_job_id.clone(), self.save_session).await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
)
.await?;
}
if interactive {output::hide_thinking()};
let _ = progress_bars.hide();
@@ -1099,14 +1114,15 @@ impl Session {
self.messages.push(response_message);
// No need for description update here
session::persist_messages_with_schedule_id(
&self.session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
self.save_session,
)
.await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
)
.await?;
}
let prompt = format!(
"The existing call to {} was interrupted. How would you like to proceed?",
@@ -1115,14 +1131,15 @@ impl Session {
self.messages.push(Message::assistant().with_text(&prompt));
// No need for description update here
session::persist_messages_with_schedule_id(
&self.session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
self.save_session,
)
.await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
)
.await?;
}
output::render_message(&Message::assistant().with_text(&prompt), self.debug);
} else {
@@ -1136,14 +1153,15 @@ impl Session {
self.messages.push(Message::assistant().with_text(prompt));
// No need for description update here
session::persist_messages_with_schedule_id(
&self.session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
self.save_session,
)
.await?;
if let Some(session_file) = &self.session_file {
session::persist_messages_with_schedule_id(
session_file,
&self.messages,
None,
self.scheduled_job_id.clone(),
)
.await?;
}
output::render_message(
&Message::assistant().with_text(prompt),
@@ -1167,7 +1185,7 @@ impl Session {
Ok(())
}
pub fn session_file(&self) -> PathBuf {
pub fn session_file(&self) -> Option<PathBuf> {
self.session_file.clone()
}
@@ -1243,11 +1261,11 @@ impl Session {
/// Get the session metadata
pub fn get_metadata(&self) -> Result<session::SessionMetadata> {
if !self.session_file.exists() {
if !self.session_file.as_ref().is_some_and(|f| f.exists()) {
return Err(anyhow::anyhow!("Session file does not exist"));
}
session::read_metadata(&self.session_file)
session::read_metadata(self.session_file.as_ref().unwrap())
}
// Get the session's total token usage
+4 -4
View File
@@ -9,7 +9,7 @@ use serde_json::Value;
use std::cell::RefCell;
use std::collections::HashMap;
use std::io::Error;
use std::path::Path;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
@@ -550,12 +550,12 @@ pub fn display_session_info(
resume: bool,
provider: &str,
model: &str,
session_file: &Path,
session_file: &Option<PathBuf>,
provider_instance: Option<&Arc<dyn goose::providers::base::Provider>>,
) {
let start_session_msg = if resume {
"resuming session |"
} else if session_file.to_str() == Some("/dev/null") || session_file.to_str() == Some("NUL") {
} else if session_file.is_none() {
"running without session |"
} else {
"starting session |"
@@ -597,7 +597,7 @@ pub fn display_session_info(
);
}
if session_file.to_str() != Some("/dev/null") && session_file.to_str() != Some("NUL") {
if let Some(session_file) = session_file {
println!(
" {} {}",
style("logging to").dim(),