use std::path::{Path, PathBuf};
use crate::cli_runtime::CliPrompt;
use super::PromptSave;
const UNSENT_PROMPT_FILE: &str = "unsent-prompt.json";
const LEGACY_UNSENT_PROMPT_FILE: &str = "unsent-prompt.txt";
pub(super) struct UnsentPrompt {
path: PathBuf,
legacy_path: PathBuf,
}
impl UnsentPrompt {
pub(super) fn in_folder(artifacts: &Path) -> Self {
Self {
path: artifacts.join(UNSENT_PROMPT_FILE),
legacy_path: artifacts.join(LEGACY_UNSENT_PROMPT_FILE),
}
}
pub(super) fn track(&self, save: &PromptSave, sent: &CliPrompt) {
let written = match save {
PromptSave::First(_) => serde_json::to_vec(sent)
.map_err(std::io::Error::other)
.and_then(|bytes| crate::config_writer::write_bytes_atomically(&self.path, &bytes))
.and_then(|()| remove_if_present(&self.legacy_path)),
PromptSave::OnceSent(_) => self.clear(),
PromptSave::Saved => Ok(()),
};
if let Err(error) = written {
tracing::warn!(
path = %self.path.display(),
%error,
"could not note the prompt the turn's run has yet to send"
);
}
}
pub(super) fn read(&self) -> Option<CliPrompt> {
if let Ok(bytes) = std::fs::read(&self.path) {
if let Ok(prompt) = serde_json::from_slice::<CliPrompt>(&bytes) {
return Some(prompt);
}
}
std::fs::read_to_string(&self.legacy_path)
.ok()
.map(CliPrompt::text)
}
pub(super) fn sent(&self) {
if let Err(error) = self.clear() {
tracing::warn!(
path = %self.path.display(),
%error,
"could not clear the prompt the turn's run sent"
);
}
}
fn clear(&self) -> std::io::Result<()> {
remove_if_present(&self.path)?;
remove_if_present(&self.legacy_path)
}
}
fn remove_if_present(path: &Path) -> std::io::Result<()> {
match std::fs::remove_file(path) {
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
removed => removed,
}
}