Skip to main content

acp_cli/session/
persistence.rs

1use serde::{Deserialize, Serialize};
2use std::io;
3use std::path::{Path, PathBuf};
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct SessionRecord {
7    pub id: String,
8    pub agent: String,
9    pub cwd: PathBuf,
10    pub name: Option<String>,
11    pub created_at: u64,
12    pub closed: bool,
13    /// The latest ACP session ID from the bridge (updated on each reconnect).
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub acp_session_id: Option<String>,
16}
17
18impl SessionRecord {
19    /// Write this session record as JSON to the given file path.
20    pub fn save(&self, path: &Path) -> io::Result<()> {
21        if let Some(parent) = path.parent() {
22            std::fs::create_dir_all(parent)?;
23        }
24        let json = serde_json::to_string_pretty(self)
25            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
26        std::fs::write(path, json)
27    }
28
29    /// Update the ACP session ID (for when the agent is re-spawned) and persist.
30    pub fn update_acp_session_id(&mut self, new_id: String, path: &Path) -> io::Result<()> {
31        self.acp_session_id = Some(new_id);
32        self.save(path)
33    }
34
35    /// Load a session record from a JSON file. Returns `None` if the file does not exist.
36    pub fn load(path: &Path) -> io::Result<Option<Self>> {
37        match std::fs::read_to_string(path) {
38            Ok(contents) => {
39                let record: Self = serde_json::from_str(&contents)
40                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
41                Ok(Some(record))
42            }
43            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
44            Err(e) => Err(e),
45        }
46    }
47}