Skip to main content

termden_core/
state.rs

1//! Persisted session state: which workspaces exist, their harnesses and tile
2//! layouts. Harness processes themselves live in tmux and outlive the app;
3//! this file is what lets a restarted (or hot-reloaded) UI find them again.
4
5use std::collections::HashMap;
6use std::env;
7use std::fs;
8use std::path::PathBuf;
9
10use serde::{Deserialize, Serialize};
11
12use crate::{
13    Activity, Choice, HarnessId, HarnessStatus, LayoutNode, Mail, Showcase, Workspace, WorkspaceId,
14};
15
16#[derive(Debug, Clone, Default, Serialize, Deserialize)]
17#[serde(default)]
18pub struct AppState {
19    pub workspaces: Vec<Workspace>,
20    pub layouts: HashMap<WorkspaceId, LayoutNode>,
21    pub active: Option<WorkspaceId>,
22    pub focused: Option<HarnessId>,
23    pub mail: Vec<Mail>,
24    pub activity: Vec<Activity>,
25    pub choices: Vec<Choice>,
26    pub showcases: Vec<Showcase>,
27}
28
29impl AppState {
30    /// `$TERMDEN_STATE_FILE`, else `$XDG_STATE_HOME/termden/state.json`.
31    pub fn path() -> PathBuf {
32        match env::var("TERMDEN_STATE_FILE") {
33            Ok(path) if !path.is_empty() => PathBuf::from(path),
34            _ => state_dir().join("state.json"),
35        }
36    }
37
38    /// Missing file means a fresh start; a corrupt one is kept aside rather
39    /// than overwritten, so a bad write never silently loses workspaces.
40    pub fn load() -> Option<Self> {
41        let path = Self::path();
42        let text = fs::read_to_string(&path).ok()?;
43        match serde_json::from_str::<Self>(&text) {
44            Ok(mut state) => {
45                // Live statuses are re-derived from the running sessions.
46                for harness in state
47                    .workspaces
48                    .iter_mut()
49                    .flat_map(|w| w.harnesses.iter_mut())
50                {
51                    harness.status = HarnessStatus::Idle;
52                }
53                Some(state)
54            }
55            Err(error) => {
56                let backup = path.with_extension("json.corrupt");
57                eprintln!(
58                    "termden: could not parse {} ({error}); moved to {}",
59                    path.display(),
60                    backup.display()
61                );
62                let _ = fs::rename(&path, backup);
63                None
64            }
65        }
66    }
67
68    /// Atomic write: temp file + rename.
69    pub fn save(&self) -> std::io::Result<()> {
70        let path = Self::path();
71        if let Some(parent) = path.parent() {
72            fs::create_dir_all(parent)?;
73        }
74        let tmp = path.with_extension("json.tmp");
75        let text = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
76        fs::write(&tmp, text)?;
77        fs::rename(tmp, path)
78    }
79
80    pub fn next_harness_id(&self) -> HarnessId {
81        // Activity lines remember the harness they are about. Never hand their
82        // id to a newcomer: an old "so-and-so left" line would then be painted
83        // in the new agent's colour.
84        let max = self
85            .workspaces
86            .iter()
87            .flat_map(|w| w.harnesses.iter())
88            .map(|h| h.id.raw())
89            .chain(
90                self.activity
91                    .iter()
92                    .filter_map(|entry| entry.harness.map(|id| id.raw())),
93            )
94            .max()
95            .unwrap_or(0);
96        HarnessId::new(max + 1)
97    }
98
99    pub fn next_workspace_id(&self) -> WorkspaceId {
100        let max = self
101            .workspaces
102            .iter()
103            .map(|w| w.id.raw())
104            .max()
105            .unwrap_or(0);
106        WorkspaceId::new(max + 1)
107    }
108}
109
110pub fn state_dir() -> PathBuf {
111    xdg_dir("XDG_STATE_HOME", ".local/state").join("termden")
112}
113
114/// `$XDG_RUNTIME_DIR/termden`, home of the control socket.
115pub fn runtime_dir() -> PathBuf {
116    match env::var("XDG_RUNTIME_DIR") {
117        Ok(dir) if !dir.is_empty() => PathBuf::from(dir).join("termden"),
118        _ => env::temp_dir().join(format!("termden-{}", env::var("USER").unwrap_or_default())),
119    }
120}
121
122/// Control socket the running app listens on. Overridable for tests.
123pub fn control_socket() -> PathBuf {
124    match env::var("TERMDEN_CONTROL_SOCKET") {
125        Ok(path) if !path.is_empty() => PathBuf::from(path),
126        _ => runtime_dir().join("app.sock"),
127    }
128}
129
130pub(crate) fn xdg_dir(var: &str, fallback: &str) -> PathBuf {
131    if let Ok(dir) = env::var(var) {
132        if !dir.is_empty() {
133            return PathBuf::from(dir);
134        }
135    }
136    match env::var("HOME") {
137        Ok(home) => PathBuf::from(home).join(fallback),
138        Err(_) => PathBuf::from(fallback),
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use crate::{Axis, Harness, HarnessKind};
146
147    #[test]
148    fn round_trips_through_json() {
149        let ws = WorkspaceId::new(1);
150        let mut state = AppState {
151            workspaces: vec![Workspace {
152                id: ws,
153                name: "w".into(),
154                path: "/tmp".into(),
155                accent: 0,
156                expanded: true,
157                harnesses: vec![Harness {
158                    id: HarnessId::new(4),
159                    workspace: ws,
160                    name: "shell".into(),
161                    kind: HarnessKind::Shell,
162                    cwd: ".".into(),
163                    status: HarnessStatus::Working,
164                    subagents: vec![],
165                    unread: 0,
166                    tag: String::new(),
167                    title: String::new(),
168                    pronouns: String::new(),
169                    color: None,
170                    announced: true,
171                    started: true,
172                }],
173            }],
174            active: Some(ws),
175            focused: Some(HarnessId::new(4)),
176            ..Default::default()
177        };
178        state.layouts.insert(
179            ws,
180            LayoutNode::split(
181                Axis::Vertical,
182                0.4,
183                LayoutNode::leaf(HarnessId::new(4)),
184                LayoutNode::leaf(HarnessId::new(5)),
185            ),
186        );
187
188        let text = serde_json::to_string(&state).unwrap();
189        let back: AppState = serde_json::from_str(&text).unwrap();
190        assert_eq!(
191            back.layouts[&ws].leaves(),
192            [HarnessId::new(4), HarnessId::new(5)]
193        );
194        assert_eq!(back.next_harness_id(), HarnessId::new(5));
195        assert_eq!(back.next_workspace_id(), WorkspaceId::new(2));
196    }
197
198    #[test]
199    fn ids_are_not_reused_while_activity_still_remembers_them() {
200        // A departed agent keeps a line in the feed. Handing its id to the
201        // next agent would repaint that line in the newcomer's colour.
202        let state = AppState {
203            activity: vec![Activity {
204                time: "00:00".into(),
205                name: "gone".into(),
206                message: "left".into(),
207                accent: 0,
208                to: None,
209                harness: Some(HarnessId::new(7)),
210            }],
211            ..Default::default()
212        };
213        assert_eq!(state.next_harness_id(), HarnessId::new(8));
214    }
215}