use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use crate::engine::config::Config;
use crate::engine::note::Note;
use crate::engine::rules::{self, Facts, SingleWindowClose, TabState, TerminalShape};
use crate::engine::tabs::Seen;
use crate::procs::{self, ProcessTable};
pub const STATE_DIR_VAR: &str = "KAERU_STATE_DIR";
const LOG_LIMIT: u64 = 256 * 1024;
pub struct Store {
dir: PathBuf,
config: PathBuf,
}
#[derive(Debug, Clone)]
pub struct StoredNote {
pub path: PathBuf,
pub note: Note,
}
#[derive(Debug, Clone)]
pub struct Reviewed {
pub stored: StoredNote,
pub state: TabState,
}
impl Store {
pub fn open() -> Result<Store> {
if let Some(dir) = std::env::var_os(STATE_DIR_VAR) {
return Store::at(PathBuf::from(dir));
}
let mut store =
Store::at(default_dir().context("this system has no folder for app state")?)?;
if let Some(config) = dirs::config_dir() {
store.config = config.join("kaeru").join("config.toml");
}
Ok(store)
}
pub fn at(dir: PathBuf) -> Result<Store> {
let notes = dir.join("notes");
fs::create_dir_all(¬es).with_context(|| format!("can't create {}", notes.display()))?;
let config = dir.join("config.toml");
Ok(Store { dir, config })
}
pub fn config(&self) -> Config {
let Ok(text) = fs::read_to_string(&self.config) else {
return Config::default();
};
toml::from_str(&text).unwrap_or_else(|error| {
self.log(&format!("can't read {}: {error}", self.config.display()));
Config::default()
})
}
pub fn save_config(&self, config: &Config) -> Result<()> {
if let Some(folder) = self.config.parent() {
fs::create_dir_all(folder)?;
}
fs::write(&self.config, toml::to_string(config)?)
.with_context(|| format!("can't write {}", self.config.display()))
}
pub fn read(&self, path: &Path) -> Result<Note> {
read_note(path)
}
pub fn notes(&self) -> Vec<StoredNote> {
let Ok(entries) = fs::read_dir(self.notes_dir()) else {
return Vec::new();
};
let mut notes: Vec<StoredNote> = entries
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.filter(|path| {
path.extension()
.is_some_and(|extension| extension == "json")
})
.filter_map(|path| match read_note(&path) {
Ok(note) => Some(StoredNote { path, note }),
Err(error) => {
self.log(&format!("skipped {}: {error:#}", path.display()));
None
}
})
.collect();
notes.sort_by_key(|stored| stored.note.process().started_ms);
notes
}
pub fn path_of(&self, note: &Note) -> PathBuf {
self.notes_dir().join(file_name(note))
}
pub fn save(&self, note: &Note) -> Result<PathBuf> {
let path = self.path_of(note);
let temp = path.with_extension(format!("json.{}.tmp", std::process::id()));
fs::write(&temp, serde_json::to_vec_pretty(note)?)
.with_context(|| format!("can't write {}", temp.display()))?;
if let Err(error) = fs::rename(&temp, &path) {
let _ = fs::remove_file(&temp);
return Err(error).with_context(|| format!("can't write {}", path.display()));
}
Ok(path)
}
pub fn remove(&self, stored: &StoredNote) {
let _ = fs::remove_file(&stored.path);
let _ = fs::remove_file(cwd_file(&stored.path));
}
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn delete_all(&self) -> Result<()> {
let notes = self.notes_dir();
if notes.exists() {
fs::remove_dir_all(¬es)
.with_context(|| format!("can't delete {}", notes.display()))?;
}
for file in [self.dir.join("lock"), self.log_path(), self.config.clone()] {
let _ = fs::remove_file(file);
}
let _ = fs::remove_dir(&self.dir);
if let Some(folder) = self.config.parent() {
let _ = fs::remove_dir(folder);
}
Ok(())
}
pub fn try_lock(&self) -> Result<Option<File>> {
let path = self.dir.join("lock");
let file = OpenOptions::new()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.with_context(|| format!("can't open {}", path.display()))?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Err(TryLockError::WouldBlock) => Ok(None),
Err(TryLockError::Error(error)) => {
Err(error).with_context(|| format!("can't lock {}", path.display()))
}
}
}
pub fn log_path(&self) -> PathBuf {
self.dir.join("kaeru.log")
}
pub fn log(&self, message: &str) {
let path = self.log_path();
if fs::metadata(&path).is_ok_and(|metadata| metadata.len() > LOG_LIMIT) {
let _ = fs::remove_file(&path);
}
let seconds = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_secs());
if let Ok(mut file) = OpenOptions::new().create(true).append(true).open(&path) {
let _ = writeln!(file, "{seconds} [{}] {message}", std::process::id());
}
}
fn notes_dir(&self) -> PathBuf {
self.dir.join("notes")
}
}
pub fn file_name(note: &Note) -> String {
let kind = match note {
Note::Shell(_) => "shell",
Note::Agent(_) => "agent",
};
let process = note.process();
format!("{kind}-{}-{}.json", process.pid, process.started_ms)
}
pub fn cwd_file(note_path: &Path) -> PathBuf {
note_path.with_extension("cwd")
}
pub fn last_seen(stored: &StoredNote) -> Seen {
let recorded = match &stored.note {
Note::Shell(note) => ¬e.cwd,
Note::Agent(note) => ¬e.cwd,
};
let file = cwd_file(&stored.path);
let cwd = fs::read_to_string(&file)
.ok()
.map(|text| text.trim().to_string())
.filter(|text| !text.is_empty())
.unwrap_or_else(|| recorded.clone());
let prompt_ms = fs::metadata(&file)
.and_then(|metadata| metadata.modified())
.ok()
.and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
.and_then(|since| u64::try_from(since.as_millis()).ok());
Seen { cwd, prompt_ms }
}
pub fn review(
store: &Store,
table: &dyn ProcessTable,
session: &str,
single_window_close: SingleWindowClose,
) -> Vec<Reviewed> {
let mut kept = Vec::new();
for stored in store.notes() {
let terminal = stored.note.terminal();
let facts = Facts {
program: procs::liveness(table, stored.note.process()),
terminal: terminal.map(|terminal| procs::liveness(table, &terminal.process)),
shape: terminal.map_or(TerminalShape::SingleWindow, |terminal| terminal.shape),
same_session: stored.note.session() == session,
single_window_close,
};
let state = rules::decide(&facts);
if state == TabState::Closed {
store.remove(&stored);
} else {
kept.push(Reviewed { stored, state });
}
}
kept
}
fn read_note(path: &Path) -> Result<Note> {
Ok(serde_json::from_str(&fs::read_to_string(path)?)?)
}
fn default_dir() -> Option<PathBuf> {
#[cfg(target_os = "linux")]
let base = dirs::state_dir();
#[cfg(not(target_os = "linux"))]
let base = dirs::data_local_dir();
base.map(|dir| dir.join("kaeru"))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::engine::note::{ProcessRef, ShellNote, TerminalRef};
use crate::procs::fake::FakeTable;
fn temp_store() -> (tempfile::TempDir, Store) {
let dir = tempfile::tempdir().unwrap();
let store = Store::at(dir.path().to_path_buf()).unwrap();
(dir, store)
}
fn shell(pid: u32, started_ms: u64, terminal: Option<(u32, u64)>) -> Note {
Note::Shell(ShellNote {
process: ProcessRef { pid, started_ms },
shell: "powershell".into(),
cwd: r"C:\Users\demo\code\api-server".into(),
terminal: terminal.map(|(pid, started_ms)| TerminalRef {
adapter: "windows-terminal".into(),
process: ProcessRef { pid, started_ms },
shape: TerminalShape::Tabs,
tab_id: None,
profile: None,
exe: None,
}),
session: "win-1".into(),
offered: false,
})
}
#[test]
fn a_saved_note_reads_back() {
let (_dir, store) = temp_store();
let note = shell(10, 1_000, None);
let path = store.save(¬e).unwrap();
assert!(path.ends_with("shell-10-1000.json"));
let notes = store.notes();
assert_eq!(notes.len(), 1);
assert_eq!(notes[0].note, note);
}
#[test]
fn saving_the_same_process_again_replaces_its_note() {
let (_dir, store) = temp_store();
store.save(&shell(10, 1_000, None)).unwrap();
store.save(&shell(10, 1_000, Some((1, 500)))).unwrap();
let notes = store.notes();
assert_eq!(notes.len(), 1);
assert!(notes[0].note.terminal().is_some());
}
#[test]
fn removing_a_note_also_removes_its_cwd_file() {
let (_dir, store) = temp_store();
let path = store.save(&shell(10, 1_000, None)).unwrap();
fs::write(cwd_file(&path), "D:\\work").unwrap();
store.remove(&store.notes()[0]);
assert!(!path.exists());
assert!(!cwd_file(&path).exists());
}
#[test]
fn an_unreadable_note_is_skipped_and_logged() {
let (dir, store) = temp_store();
fs::write(dir.path().join("notes").join("shell-1-1.json"), "not json").unwrap();
assert!(store.notes().is_empty());
let log = fs::read_to_string(store.log_path()).unwrap();
assert!(log.contains("skipped"));
}
#[test]
fn the_last_folder_comes_from_the_cwd_file() {
let (_dir, store) = temp_store();
let path = store.save(&shell(10, 1_000, None)).unwrap();
let stored = store.notes().remove(0);
assert_eq!(last_seen(&stored).cwd, r"C:\Users\demo\code\api-server");
fs::write(cwd_file(&path), "D:\\work\\프로젝트\r\n").unwrap();
assert_eq!(last_seen(&stored).cwd, "D:\\work\\프로젝트");
}
#[test]
fn only_one_holder_gets_the_lock() {
let (_dir, store) = temp_store();
let first = store.try_lock().unwrap();
assert!(first.is_some());
assert!(store.try_lock().unwrap().is_none());
drop(first);
assert!(store.try_lock().unwrap().is_some());
}
#[test]
fn review_deletes_closed_tabs_and_keeps_the_rest() {
let (_dir, store) = temp_store();
let open = store.save(&shell(10, 1_000, Some((1, 500)))).unwrap();
let closed = store.save(&shell(20, 2_000, Some((1, 500)))).unwrap();
let waiting = store.save(&shell(30, 3_000, Some((2, 600)))).unwrap();
let table = FakeTable::new(&[
(10, Some(1), "powershell.exe", Some(1_000)),
(1, None, "WindowsTerminal.exe", Some(500)),
]);
let reviewed = review(&store, &table, "win-1", SingleWindowClose::Forget);
let states: Vec<(&Path, TabState)> = reviewed
.iter()
.map(|reviewed| (reviewed.stored.path.as_path(), reviewed.state))
.collect();
assert_eq!(
states,
[
(open.as_path(), TabState::Open),
(waiting.as_path(), TabState::Waiting)
]
);
assert!(!closed.exists());
}
#[test]
fn options_are_saved_and_read_back() {
let (_dir, store) = temp_store();
assert_eq!(store.config(), Config::default(), "no file yet");
let config = Config {
offer_shells: false,
..Config::default()
};
store.save_config(&config).unwrap();
assert_eq!(store.config(), config);
}
#[test]
fn a_broken_config_file_gives_the_defaults_and_is_logged() {
let (dir, store) = temp_store();
fs::write(dir.path().join("config.toml"), "offer-shells = maybe").unwrap();
assert_eq!(store.config(), Config::default());
let log = fs::read_to_string(store.log_path()).unwrap();
assert!(log.contains("config.toml"));
}
}