Skip to main content

agent_ssh/
workspace.rs

1use std::{fs, path::Path};
2
3use anyhow::{Context, Result, bail};
4use serde::{Deserialize, Serialize};
5
6use crate::grid::{Step, grid_steps};
7
8#[derive(Debug, Serialize, Deserialize)]
9#[serde(deny_unknown_fields)]
10pub struct Workspace {
11    pub version: u32,
12    pub panes_per_tab: usize,
13    pub panes: Vec<Pane>,
14}
15
16#[derive(Debug, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct Pane {
19    pub title: String,
20    #[serde(default, skip_serializing_if = "Option::is_none")]
21    pub cwd: Option<String>,
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub profile: Option<String>,
24    pub command: Vec<String>,
25}
26
27impl Workspace {
28    pub fn read(path: &Path) -> Result<Self> {
29        let text = fs::read_to_string(path)
30            .with_context(|| format!("cannot read workspace {}", path.display()))?;
31        let workspace: Self = serde_json::from_str(text.trim_start_matches('\u{feff}'))
32            .with_context(|| format!("invalid workspace {}", path.display()))?;
33        workspace.validate()?;
34        Ok(workspace)
35    }
36
37    pub fn validate(&self) -> Result<()> {
38        if self.version != 1 {
39            bail!("unsupported workspace version {}; expected 1", self.version);
40        }
41        if self.panes_per_tab == 0 || self.panes_per_tab > 16 {
42            bail!("panes_per_tab must be between 1 and 16");
43        }
44        if self.panes.is_empty() {
45            bail!("workspace contains no panes");
46        }
47        for pane in &self.panes {
48            if pane.command.first().is_none_or(|s| s.trim().is_empty()) {
49                bail!("pane '{}' needs a command executable", pane.title);
50            }
51            // Windows Terminal parses semicolons as action separators, even inside
52            // command arguments. Reject them rather than accidentally creating actions.
53            for value in pane
54                .command
55                .iter()
56                .chain([&pane.title])
57                .chain(pane.cwd.iter())
58                .chain(pane.profile.iter())
59            {
60                if value.contains([';', '\0', '\r', '\n']) {
61                    bail!(
62                        "pane '{}' contains a Terminal action separator or control character",
63                        pane.title
64                    );
65                }
66            }
67        }
68        Ok(())
69    }
70
71    pub fn write(&self, path: &Path) -> Result<()> {
72        self.validate()?;
73        // A saved workspace may be the only recovery copy. Never overwrite it implicitly.
74        use std::io::Write;
75        let mut file = fs::OpenOptions::new()
76            .write(true)
77            .create_new(true)
78            .open(path)
79            .with_context(|| {
80                format!(
81                    "cannot create workspace {} (choose a new filename if it exists)",
82                    path.display()
83                )
84            })?;
85        file.write_all(serde_json::to_string_pretty(self)?.as_bytes())?;
86        file.write_all(b"\n")?;
87        Ok(())
88    }
89
90    pub fn wt_args(&self, window: &str, panes_per_tab: Option<usize>) -> Result<Vec<String>> {
91        self.validate()?;
92        let count = panes_per_tab.unwrap_or(self.panes_per_tab);
93        if !(1..=16).contains(&count) {
94            bail!("panes per tab must be between 1 and 16");
95        }
96        let mut args = vec!["-w".into(), window.into()];
97        for tab in self.panes.chunks(count) {
98            for step in grid_steps(tab) {
99                if args.len() > 2 {
100                    args.push(";".into());
101                }
102                match step {
103                    Step::New(pane) => {
104                        args.push("nt".into());
105                        args.extend(pane_args(pane));
106                    }
107                    Step::Split {
108                        direction,
109                        size,
110                        target,
111                    } => {
112                        args.extend([
113                            "sp".into(),
114                            direction.wt_flag().into(),
115                            "--size".into(),
116                            format!("{size:.4}"),
117                        ]);
118                        args.extend(pane_args(target));
119                    }
120                    Step::FocusLeft => args.extend(["mf".into(), "left".into()]),
121                }
122            }
123            args.extend([";".into(), "mf".into(), "first".into()]);
124        }
125        Ok(args)
126    }
127}
128
129fn pane_args(pane: &Pane) -> Vec<String> {
130    let mut args = vec!["--title".into(), pane.title.clone()];
131    if let Some(profile) = &pane.profile {
132        args.extend(["-p".into(), profile.clone()]);
133    }
134    if let Some(cwd) = &pane.cwd {
135        args.extend(["-d".into(), cwd.clone()]);
136    }
137    args.extend(pane.command.clone());
138    args
139}
140
141/// Merge an explicitly counted run of single-pane tabs. Only Terminal layout
142/// actions are emitted: this never launches or terminates a shell/agent.
143pub fn regroup_args(window: &str, tabs: usize, first: usize) -> Result<Vec<String>> {
144    if tabs == 0 {
145        bail!("regroup requires at least one existing tab");
146    }
147    if tabs > 1024 || first.checked_add(tabs).is_none() {
148        bail!("invalid regroup tab range (maximum 1024 tabs)");
149    }
150    let mut args = vec!["-w".into(), window.into()];
151    for offset in (0..tabs).step_by(4) {
152        let target = first + offset / 4;
153        for member in 1..(tabs - offset).min(4) {
154            if args.len() > 2 {
155                args.push(";".into());
156            }
157            if member > 1 {
158                args.extend([
159                    "ft".into(),
160                    "-t".into(),
161                    target.to_string(),
162                    ";".into(),
163                    "mf".into(),
164                    if member == 2 {
165                        "first".into()
166                    } else {
167                        "right".into()
168                    },
169                    ";".into(),
170                ]);
171            }
172            args.extend([
173                "ft".into(),
174                "-t".into(),
175                (target + 1).to_string(),
176                ";".into(),
177                "move-pane".into(),
178                "-t".into(),
179                target.to_string(),
180            ]);
181        }
182    }
183    if args.len() == 2 {
184        args.extend(["ft".into(), "-t".into(), first.to_string()]);
185    }
186    Ok(args)
187}
188
189#[cfg(test)]
190mod tests {
191    use super::*;
192
193    fn workspace(count: usize) -> Workspace {
194        Workspace {
195            version: 1,
196            panes_per_tab: 4,
197            panes: (0..count)
198                .map(|i| Pane {
199                    title: format!("pane-{i}"),
200                    cwd: Some(r"C:\Work Projects".into()),
201                    profile: None,
202                    command: vec!["codex.cmd".into(), "resume".into(), format!("thread-{i}")],
203                })
204                .collect(),
205        }
206    }
207
208    #[test]
209    fn sixteen_sessions_restore_as_four_grids_without_losing_commands() {
210        let args = workspace(16).wt_args("recovery", None).unwrap();
211        assert_eq!(args.iter().filter(|s| *s == "nt").count(), 4);
212        assert_eq!(args.iter().filter(|s| *s == "sp").count(), 12);
213        for i in 0..16 {
214            assert_eq!(
215                args.iter().filter(|s| **s == format!("thread-{i}")).count(),
216                1
217            );
218        }
219        assert_eq!(
220            args.iter().filter(|s| *s == r"C:\Work Projects").count(),
221            16
222        );
223        assert_eq!(args.iter().filter(|s| *s == "-V").count(), 4);
224        assert_eq!(args.iter().filter(|s| *s == "-H").count(), 8);
225    }
226
227    #[test]
228    fn partial_tabs_and_single_pane_work() {
229        let args = workspace(5).wt_args("new", None).unwrap();
230        assert_eq!(args.iter().filter(|s| *s == "nt").count(), 2);
231        assert_eq!(args.iter().filter(|s| *s == "sp").count(), 3);
232        assert!(workspace(1).wt_args("new", None).is_ok());
233        assert!(workspace(1).wt_args("new", Some(0)).is_err());
234    }
235
236    #[test]
237    fn rejects_bad_workspace_and_terminal_action_injection() {
238        assert!(workspace(0).validate().is_err());
239        let mut w = workspace(1);
240        w.panes[0].command.push(";nt".into());
241        assert!(w.validate().is_err());
242        w.panes[0].command.clear();
243        assert!(w.validate().is_err());
244        w.version = 2;
245        assert!(w.validate().is_err());
246    }
247
248    #[test]
249    fn regroup_only_moves_existing_panes_with_shifting_tab_indices() {
250        let args = regroup_args("recovery", 16, 0).unwrap();
251        assert_eq!(args.iter().filter(|s| *s == "move-pane").count(), 12);
252        assert!(
253            !args
254                .iter()
255                .any(|s| ["nt", "sp", "ssh.exe", "codex"].contains(&s.as_str()))
256        );
257        let moves: Vec<_> = args
258            .windows(3)
259            .filter(|s| s[0] == "move-pane")
260            .map(|s| s[2].as_str())
261            .collect();
262        assert_eq!(
263            moves,
264            ["0", "0", "0", "1", "1", "1", "2", "2", "2", "3", "3", "3"]
265        );
266        assert!(regroup_args("recovery", 0, 0).is_err());
267    }
268}