Skip to main content

agent_ssh/
snapshot.rs

1use std::{collections::HashSet, fs, io::Write, path::Path};
2
3use anyhow::{Context, Result, bail};
4use serde::{Deserialize, Serialize};
5
6const MAX_PANES: usize = 256;
7const MAX_DEPTH: usize = 32;
8const EPS: f64 = 0.01;
9const MAX_GAP: f64 = 8.0;
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct SavedState {
14    pub version: u32,
15    pub restorable: bool,
16    pub tabs: Vec<SavedTab>,
17    pub selected_tab: Option<usize>,
18}
19
20#[derive(Clone, Debug, Serialize, Deserialize)]
21#[serde(deny_unknown_fields)]
22pub struct SavedTab {
23    pub title: String,
24    pub root: PaneTree,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub focused_pane: Option<String>,
27}
28
29#[derive(Clone, Debug, Serialize, Deserialize)]
30#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
31pub enum PaneTree {
32    Pane {
33        pane: SavedPane,
34    },
35    Split {
36        axis: Axis,
37        first_fraction: f64,
38        first: Box<PaneTree>,
39        second: Box<PaneTree>,
40    },
41}
42
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum Axis {
46    Vertical,
47    Horizontal,
48}
49
50#[derive(Clone, Debug, Serialize, Deserialize)]
51#[serde(deny_unknown_fields)]
52pub struct SavedPane {
53    pub key: String,
54    pub title: String,
55    pub target: RecoveryTarget,
56}
57
58#[derive(Clone, Debug, Serialize, Deserialize)]
59#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
60pub enum RecoveryTarget {
61    Unavailable {
62        reason: String,
63    },
64    FreshShell {
65        executable: String,
66        cwd: String,
67    },
68    LocalCodex {
69        executable: String,
70        thread_id: String,
71        cwd: String,
72        yolo: bool,
73    },
74    RemoteTmux {
75        host: String,
76        socket: String,
77        session: String,
78        remote_program: String,
79    },
80}
81
82#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
83#[serde(deny_unknown_fields)]
84pub struct Rect {
85    pub x: f64,
86    pub y: f64,
87    pub width: f64,
88    pub height: f64,
89}
90
91#[derive(Clone, Debug)]
92pub struct PositionedPane {
93    pub rect: Rect,
94    pub pane: SavedPane,
95}
96
97fn text(value: &str) -> Result<()> {
98    crate::attachment::validate_text(value)?;
99    if value.len() > 8192 {
100        bail!("snapshot field exceeds size limit");
101    }
102    Ok(())
103}
104
105fn nonempty(value: &str) -> Result<()> {
106    text(value)?;
107    if value.trim().is_empty() {
108        bail!("snapshot identity or path is empty");
109    }
110    Ok(())
111}
112
113fn uuid(value: &str) -> bool {
114    value.len() == 36
115        && value.bytes().enumerate().all(|(i, b)| {
116            if [8, 13, 18, 23].contains(&i) {
117                b == b'-'
118            } else {
119                b.is_ascii_hexdigit()
120            }
121        })
122}
123
124impl SavedPane {
125    fn validate(&self) -> Result<()> {
126        nonempty(&self.key)?;
127        text(&self.title)?;
128        self.target.validate()
129    }
130}
131
132impl RecoveryTarget {
133    pub fn validate(&self) -> Result<()> {
134        match self {
135            RecoveryTarget::Unavailable { reason } => {
136                if reason.trim().is_empty()
137                    || reason.len() > 8192
138                    || reason.chars().any(char::is_control)
139                {
140                    bail!("invalid unavailable-target reason");
141                }
142            }
143            RecoveryTarget::FreshShell { executable, cwd } => {
144                nonempty(executable)?;
145                nonempty(cwd)?;
146                if executable.starts_with('-') {
147                    bail!("invalid fresh-shell executable");
148                }
149            }
150            RecoveryTarget::LocalCodex {
151                executable,
152                thread_id,
153                cwd,
154                ..
155            } => {
156                nonempty(executable)?;
157                nonempty(cwd)?;
158                if executable.starts_with('-') || !uuid(thread_id) {
159                    bail!("invalid local Codex executable or thread UUID");
160                }
161            }
162            RecoveryTarget::RemoteTmux {
163                host,
164                socket,
165                session,
166                remote_program,
167            } => {
168                for value in [host, socket, session, remote_program] {
169                    nonempty(value)?;
170                }
171                if host.starts_with('-')
172                    || host.chars().any(char::is_whitespace)
173                    || remote_program.starts_with('-')
174                    || !socket.starts_with('/')
175                {
176                    bail!("invalid SSH host, remote executable, or absolute tmux socket");
177                }
178            }
179        }
180        Ok(())
181    }
182}
183
184impl SavedPane {
185    fn args(&self) -> Vec<String> {
186        let mut args = vec!["--title".into(), self.title.clone()];
187        match &self.target {
188            RecoveryTarget::Unavailable { .. } => {
189                unreachable!("restore preflight rejects unavailable panes")
190            }
191            RecoveryTarget::FreshShell { executable, cwd } => {
192                args.extend(["-d".into(), cwd.clone(), executable.clone()]);
193            }
194            RecoveryTarget::LocalCodex {
195                executable,
196                thread_id,
197                cwd,
198                yolo,
199            } => {
200                args.extend([
201                    "-d".into(),
202                    cwd.clone(),
203                    executable.clone(),
204                    "resume".into(),
205                ]);
206                if *yolo {
207                    args.push("--dangerously-bypass-approvals-and-sandbox".into());
208                }
209                args.push(thread_id.clone());
210                args.extend(["--cd".into(), cwd.clone()]);
211            }
212            RecoveryTarget::RemoteTmux {
213                host,
214                socket,
215                session,
216                remote_program,
217            } => {
218                args.extend([
219                    "agent-ssh".into(),
220                    "tmux".into(),
221                    "--on".into(),
222                    host.clone(),
223                    "--socket".into(),
224                    socket.clone(),
225                    "--remote-program".into(),
226                    remote_program.clone(),
227                    "attach".into(),
228                    "--".into(),
229                    session.clone(),
230                ]);
231            }
232        }
233        args
234    }
235}
236
237impl PaneTree {
238    fn visit<'a>(&'a self, out: &mut Vec<&'a SavedPane>) {
239        match self {
240            Self::Pane { pane } => out.push(pane),
241            Self::Split { first, second, .. } => {
242                first.visit(out);
243                second.visit(out);
244            }
245        }
246    }
247
248    fn validate(&self, depth: usize, count: &mut usize, keys: &mut HashSet<String>) -> Result<()> {
249        if depth > MAX_DEPTH {
250            bail!("snapshot split tree exceeds depth limit");
251        }
252        match self {
253            Self::Pane { pane } => {
254                *count += 1;
255                if *count > MAX_PANES {
256                    bail!("snapshot exceeds pane limit");
257                }
258                pane.validate()?;
259                if !keys.insert(pane.key.clone()) {
260                    bail!("duplicate snapshot pane key");
261                }
262            }
263            Self::Split {
264                first_fraction,
265                first,
266                second,
267                ..
268            } => {
269                let second_fraction = 1.0 - first_fraction;
270                if !(*first_fraction > 0.0
271                    && *first_fraction < 1.0
272                    && second_fraction > 0.0
273                    && second_fraction < 1.0)
274                {
275                    bail!("split fraction must be finite and strictly between zero and one");
276                }
277                first.validate(depth + 1, count, keys)?;
278                second.validate(depth + 1, count, keys)?;
279            }
280        }
281        Ok(())
282    }
283
284    fn first(&self) -> &SavedPane {
285        match self {
286            Self::Pane { pane } => pane,
287            Self::Split { first, .. } => first.first(),
288        }
289    }
290
291    fn compile(&self, args: &mut Vec<String>) {
292        if let Self::Split {
293            axis,
294            first_fraction,
295            first,
296            second,
297        } = self
298        {
299            let mut split = vec![
300                "sp".into(),
301                if *axis == Axis::Vertical { "-V" } else { "-H" }.into(),
302                "--size".into(),
303                (1.0 - first_fraction).to_string(),
304            ];
305            split.extend(second.first().args());
306            action(args, split);
307            action(
308                args,
309                [
310                    "mf".into(),
311                    if *axis == Axis::Vertical {
312                        "left"
313                    } else {
314                        "up"
315                    }
316                    .into(),
317                ],
318            );
319            first.compile(args);
320            action(
321                args,
322                [
323                    "mf".into(),
324                    if *axis == Axis::Vertical {
325                        "right"
326                    } else {
327                        "down"
328                    }
329                    .into(),
330                ],
331            );
332            second.compile(args);
333        }
334    }
335}
336
337fn action(args: &mut Vec<String>, values: impl IntoIterator<Item = String>) {
338    if args.len() > 2 {
339        args.push(";".into());
340    }
341    args.extend(values);
342}
343
344impl SavedState {
345    pub fn parse(input: &str) -> Result<Self> {
346        if input.len() > 2 * 1024 * 1024 {
347            bail!("snapshot exceeds size limit");
348        }
349        let state: Self = serde_json::from_str(input.trim_start_matches('\u{feff}'))
350            .context("invalid version 3 snapshot JSON")?;
351        state.validate()?;
352        Ok(state)
353    }
354
355    pub fn validate(&self) -> Result<()> {
356        if self.version != 3 {
357            bail!("unsupported snapshot version; expected 3");
358        }
359        if self.tabs.is_empty() || self.tabs.len() > 64 {
360            bail!("snapshot needs 1 to 64 tabs");
361        }
362        if self.selected_tab.is_some_and(|i| i >= self.tabs.len()) {
363            bail!("selected tab is outside snapshot");
364        }
365        if self.restorable
366            == self
367                .panes()
368                .iter()
369                .any(|pane| matches!(pane.target, RecoveryTarget::Unavailable { .. }))
370        {
371            bail!("snapshot recovery status does not match its targets");
372        }
373        let mut count = 0;
374        let mut keys = HashSet::new();
375        let mut local_threads = HashSet::new();
376        for tab in &self.tabs {
377            text(&tab.title)?;
378            tab.root.validate(0, &mut count, &mut keys)?;
379            if let Some(focused) = &tab.focused_pane {
380                let mut panes = Vec::new();
381                tab.root.visit(&mut panes);
382                if !panes.iter().any(|pane| &pane.key == focused) {
383                    bail!("focused pane is outside its saved tab");
384                }
385            }
386        }
387        for pane in self.panes() {
388            if let RecoveryTarget::LocalCodex { thread_id, .. } = &pane.target
389                && !local_threads.insert(thread_id.to_ascii_lowercase())
390            {
391                bail!("multiple panes claim the same local Codex conversation");
392            }
393        }
394        Ok(())
395    }
396
397    pub fn write_new(&self, path: &Path) -> Result<()> {
398        self.validate()?;
399        let mut bytes = serde_json::to_vec_pretty(self)?;
400        bytes.push(b'\n');
401        if bytes.len() > 2 * 1024 * 1024 {
402            bail!("snapshot exceeds size limit");
403        }
404        let mut file = fs::OpenOptions::new()
405            .write(true)
406            .create_new(true)
407            .open(path)
408            .with_context(|| {
409                format!(
410                    "cannot create snapshot {}; choose a new filename",
411                    path.display()
412                )
413            })?;
414        file.write_all(&bytes)?;
415        file.sync_all()?;
416        Ok(())
417    }
418
419    pub fn panes(&self) -> Vec<&SavedPane> {
420        let mut out = Vec::new();
421        for tab in &self.tabs {
422            tab.root.visit(&mut out);
423        }
424        out
425    }
426
427    pub fn wt_args(&self, window: &str, include_focus: bool) -> Result<Vec<String>> {
428        self.validate()?;
429        if !self.restorable {
430            bail!("snapshot contains unavailable recovery targets");
431        }
432        nonempty(window)?;
433        let mut args = vec!["-w".into(), window.into()];
434        for tab in &self.tabs {
435            let mut new = vec!["nt".into()];
436            new.extend(tab.root.first().args());
437            action(&mut args, new);
438            tab.root.compile(&mut args);
439            action(&mut args, ["mf".into(), "first".into()]);
440            if let Some(key) = &tab.focused_pane {
441                let mut panes = Vec::new();
442                tab.root.visit(&mut panes);
443                let ordinal = panes.iter().position(|pane| &pane.key == key).unwrap();
444                for _ in 0..ordinal {
445                    action(&mut args, ["mf".into(), "nextInOrder".into()]);
446                }
447            }
448        }
449        if include_focus && let Some(index) = self.selected_tab {
450            action(&mut args, ["ft".into(), "-t".into(), index.to_string()]);
451        }
452        let units: usize = args.iter().map(|s| s.encode_utf16().count() * 2 + 3).sum();
453        if units > 30_000 {
454            bail!("snapshot exceeds safe Windows command-line length");
455        }
456        Ok(args)
457    }
458}
459
460impl Rect {
461    fn end(self, axis: Axis) -> f64 {
462        self.start(axis) + self.size(axis)
463    }
464    fn start(self, axis: Axis) -> f64 {
465        if axis == Axis::Vertical {
466            self.x
467        } else {
468            self.y
469        }
470    }
471    fn size(self, axis: Axis) -> f64 {
472        if axis == Axis::Vertical {
473            self.width
474        } else {
475            self.height
476        }
477    }
478    fn valid(self) -> bool {
479        [
480            self.x,
481            self.y,
482            self.width,
483            self.height,
484            self.x + self.width,
485            self.y + self.height,
486        ]
487        .iter()
488        .all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
489            && self.width > EPS
490            && self.height > EPS
491    }
492}
493
494fn bounds(panes: &[PositionedPane]) -> Rect {
495    let x = panes.iter().map(|p| p.rect.x).fold(f64::INFINITY, f64::min);
496    let y = panes.iter().map(|p| p.rect.y).fold(f64::INFINITY, f64::min);
497    let right = panes
498        .iter()
499        .map(|p| p.rect.x + p.rect.width)
500        .fold(f64::NEG_INFINITY, f64::max);
501    let bottom = panes
502        .iter()
503        .map(|p| p.rect.y + p.rect.height)
504        .fold(f64::NEG_INFINITY, f64::max);
505    Rect {
506        x,
507        y,
508        width: right - x,
509        height: bottom - y,
510    }
511}
512
513pub fn reconstruct(panes: Vec<PositionedPane>) -> Result<PaneTree> {
514    if panes.is_empty() || panes.len() > MAX_PANES {
515        bail!("geometry needs 1 to 256 panes");
516    }
517    let mut keys = HashSet::new();
518    for (i, pane) in panes.iter().enumerate() {
519        pane.pane.validate()?;
520        if !pane.rect.valid() || !keys.insert(&pane.pane.key) {
521            bail!("invalid rectangle or duplicate pane key");
522        }
523        for other in &panes[..i] {
524            let a = pane.rect;
525            let b = other.rect;
526            if a.x.max(b.x) < (a.x + a.width).min(b.x + b.width) - EPS
527                && a.y.max(b.y) < (a.y + a.height).min(b.y + b.height) - EPS
528            {
529                bail!("pane rectangles overlap");
530            }
531        }
532    }
533    reconstruct_inner(panes, 0, &mut 4096)
534}
535
536fn reconstruct_inner(
537    panes: Vec<PositionedPane>,
538    depth: usize,
539    budget: &mut usize,
540) -> Result<PaneTree> {
541    if *budget == 0 {
542        bail!("geometry reconstruction exceeds work limit");
543    }
544    *budget -= 1;
545    if depth > MAX_DEPTH {
546        bail!("geometry exceeds split depth limit");
547    }
548    if panes.len() == 1 {
549        return Ok(PaneTree::Pane {
550            pane: panes.into_iter().next().unwrap().pane,
551        });
552    }
553    let parent = bounds(&panes);
554    for axis in [Axis::Vertical, Axis::Horizontal] {
555        let cross = if axis == Axis::Vertical {
556            Axis::Horizontal
557        } else {
558            Axis::Vertical
559        };
560        let mut cuts: Vec<f64> = panes.iter().map(|p| p.rect.end(axis)).collect();
561        cuts.sort_by(f64::total_cmp);
562        cuts.dedup_by(|a, b| (*a - *b).abs() < EPS);
563        for cut in cuts {
564            let (first, second): (Vec<_>, Vec<_>) = panes
565                .iter()
566                .cloned()
567                .partition(|p| p.rect.end(axis) <= cut + EPS);
568            if first.is_empty() || second.is_empty() {
569                continue;
570            }
571            let a = bounds(&first);
572            let b = bounds(&second);
573            let gap = b.start(axis) - a.end(axis);
574            if !(-EPS..=MAX_GAP).contains(&gap)
575                || second.iter().any(|p| p.rect.start(axis) < cut - EPS)
576                || (a.start(cross) - parent.start(cross)).abs() > EPS
577                || (b.start(cross) - parent.start(cross)).abs() > EPS
578                || (a.end(cross) - parent.end(cross)).abs() > EPS
579                || (b.end(cross) - parent.end(cross)).abs() > EPS
580            {
581                continue;
582            }
583            if let (Ok(first), Ok(second)) = (
584                reconstruct_inner(first, depth + 1, budget),
585                reconstruct_inner(second, depth + 1, budget),
586            ) {
587                return Ok(PaneTree::Split {
588                    axis,
589                    first_fraction: (a.end(axis) + gap / 2.0 - parent.start(axis))
590                        / parent.size(axis),
591                    first: Box::new(first),
592                    second: Box::new(second),
593                });
594            }
595        }
596    }
597    bail!("incomplete or non-guillotine pane geometry")
598}
599
600#[cfg(test)]
601mod tests {
602    use super::*;
603
604    fn pane(key: &str) -> SavedPane {
605        SavedPane {
606            key: key.into(),
607            title: key.into(),
608            target: RecoveryTarget::LocalCodex {
609                executable: "C:\\Program Files\\Codex\\codex.exe".into(),
610                thread_id: format!(
611                    "019aaaaa-1234-7890-abcd-{:012x}",
612                    key.bytes()
613                        .fold(0u64, |n, b| (n * 31 + u64::from(b)) & 0xffff_ffff_ffff)
614                ),
615                cwd: "C:\\Work Projects".into(),
616                yolo: false,
617            },
618        }
619    }
620
621    fn leaf(key: &str) -> PaneTree {
622        PaneTree::Pane { pane: pane(key) }
623    }
624
625    fn split(axis: Axis, fraction: f64, first: PaneTree, second: PaneTree) -> PaneTree {
626        PaneTree::Split {
627            axis,
628            first_fraction: fraction,
629            first: Box::new(first),
630            second: Box::new(second),
631        }
632    }
633
634    fn state(root: PaneTree) -> SavedState {
635        SavedState {
636            version: 3,
637            restorable: true,
638            tabs: vec![SavedTab {
639                title: "work".into(),
640                root,
641                focused_pane: None,
642            }],
643            selected_tab: Some(0),
644        }
645    }
646
647    fn positioned(key: &str, x: f64, y: f64, width: f64, height: f64) -> PositionedPane {
648        PositionedPane {
649            pane: pane(key),
650            rect: Rect {
651                x,
652                y,
653                width,
654                height,
655            },
656        }
657    }
658
659    #[test]
660    fn asymmetric_tabs_compile_membership_ratios_and_directional_focus() {
661        let mut saved = state(split(
662            Axis::Vertical,
663            0.4,
664            split(Axis::Horizontal, 0.6, leaf("a"), leaf("b")),
665            split(Axis::Horizontal, 0.25, leaf("c"), leaf("d")),
666        ));
667        saved.tabs.push(SavedTab {
668            title: "second".into(),
669            root: split(Axis::Vertical, 0.7, leaf("e"), leaf("f")),
670            focused_pane: Some("f".into()),
671        });
672        saved.selected_tab = Some(1);
673        let args = saved.wt_args("new", true).unwrap();
674        let actions: Vec<_> = args[2..].split(|s| s == ";").collect();
675        assert_eq!(actions.iter().filter(|a| a[0] == "nt").count(), 2);
676        let splits: Vec<_> = actions.iter().filter(|a| a[0] == "sp").collect();
677        assert_eq!(splits.len(), 4);
678        for (a, (axis, fraction)) in
679            splits
680                .iter()
681                .zip([("-V", 0.6), ("-H", 0.4), ("-H", 0.75), ("-V", 0.3)])
682        {
683            assert_eq!(a[1], axis);
684            assert!((a[3].parse::<f64>().unwrap() - fraction).abs() < 1e-10);
685        }
686        let focuses: Vec<_> = actions
687            .iter()
688            .filter(|a| a[0] == "mf")
689            .map(|a| a[1].as_str())
690            .collect();
691        assert_eq!(
692            focuses,
693            [
694                "left",
695                "up",
696                "down",
697                "right",
698                "up",
699                "down",
700                "first",
701                "left",
702                "right",
703                "first",
704                "nextInOrder"
705            ]
706        );
707        assert!(!args.iter().any(|arg| arg == "fp" || arg == "focus-pane"));
708        assert_eq!(actions.last().unwrap(), &["ft", "-t", "1"]);
709        assert!(
710            !saved
711                .wt_args("append", false)
712                .unwrap()
713                .iter()
714                .any(|s| s == "ft")
715        );
716        assert_eq!(
717            saved
718                .panes()
719                .iter()
720                .map(|p| p.key.as_str())
721                .collect::<Vec<_>>(),
722            ["a", "b", "c", "d", "e", "f"]
723        );
724    }
725
726    #[test]
727    fn six_pane_asymmetric_tree_crosses_only_unsplit_sibling_regions() {
728        let saved = state(split(
729            Axis::Vertical,
730            0.25,
731            split(Axis::Horizontal, 0.5, leaf("a"), leaf("b")),
732            split(
733                Axis::Vertical,
734                1.0 / 3.0,
735                split(Axis::Horizontal, 0.5, leaf("c"), leaf("d")),
736                split(Axis::Horizontal, 0.5, leaf("e"), leaf("f")),
737            ),
738        ));
739        let args = saved.wt_args("new", false).unwrap();
740        let actions: Vec<Vec<String>> = args[2..]
741            .split(|arg| arg == ";")
742            .map(|a| match a[0].as_str() {
743                "nt" => vec!["nt".into(), a[2].clone()],
744                "sp" => vec!["sp".into(), a[1].clone(), a[5].clone()],
745                "mf" => vec!["mf".into(), a[1].clone()],
746                _ => panic!("unexpected action"),
747            })
748            .collect();
749        let expected: Vec<Vec<String>> = [
750            vec!["nt", "a"],
751            vec!["sp", "-V", "c"],
752            vec!["mf", "left"],
753            vec!["sp", "-H", "b"],
754            vec!["mf", "up"],
755            vec!["mf", "down"],
756            vec!["mf", "right"],
757            vec!["sp", "-V", "e"],
758            vec!["mf", "left"],
759            vec!["sp", "-H", "d"],
760            vec!["mf", "up"],
761            vec!["mf", "down"],
762            vec!["mf", "right"],
763            vec!["sp", "-H", "f"],
764            vec!["mf", "up"],
765            vec!["mf", "down"],
766            vec!["mf", "first"],
767        ]
768        .into_iter()
769        .map(|a| a.into_iter().map(str::to_owned).collect())
770        .collect();
771        assert_eq!(actions, expected);
772    }
773
774    #[test]
775    fn rectangle_grid_reconstructs_canonical_equivalent_geometry() {
776        let tree = reconstruct(vec![
777            positioned("d", 604.0, 304.0, 396.0, 496.0),
778            positioned("b", 0.0, 504.0, 600.0, 296.0),
779            positioned("a", 0.0, 0.0, 600.0, 500.0),
780            positioned("c", 604.0, 0.0, 396.0, 300.0),
781        ])
782        .unwrap();
783        let PaneTree::Split {
784            axis,
785            first_fraction,
786            first,
787            second,
788        } = &tree
789        else {
790            panic!()
791        };
792        assert_eq!(*axis, Axis::Vertical);
793        assert!((*first_fraction - 0.602).abs() < 1e-10);
794        assert!(matches!(
795            first.as_ref(),
796            PaneTree::Split {
797                axis: Axis::Horizontal,
798                ..
799            }
800        ));
801        assert!(matches!(
802            second.as_ref(),
803            PaneTree::Split {
804                axis: Axis::Horizontal,
805                ..
806            }
807        ));
808        let saved = state(tree);
809        let roundtrip = SavedState::parse(&serde_json::to_string(&saved).unwrap()).unwrap();
810        assert_eq!(
811            roundtrip
812                .panes()
813                .iter()
814                .map(|p| p.key.as_str())
815                .collect::<Vec<_>>(),
816            ["a", "b", "c", "d"]
817        );
818        let symmetric = reconstruct(vec![
819            positioned("a", 0.0, 0.0, 100.0, 100.0),
820            positioned("b", 0.0, 104.0, 100.0, 100.0),
821            positioned("c", 104.0, 0.0, 100.0, 100.0),
822            positioned("d", 104.0, 104.0, 100.0, 100.0),
823        ])
824        .unwrap();
825        assert!(matches!(
826            symmetric,
827            PaneTree::Split {
828                axis: Axis::Vertical,
829                ..
830            }
831        ));
832    }
833
834    #[test]
835    fn malformed_geometry_is_rejected() {
836        for panes in [
837            vec![],
838            vec![
839                positioned("a", 0.0, 0.0, 100.0, 100.0),
840                positioned("b", 50.0, 50.0, 100.0, 100.0),
841            ],
842            vec![
843                positioned("a", 0.0, 0.0, 100.0, 100.0),
844                positioned("b", 104.0, 0.0, 100.0, 50.0),
845            ],
846            vec![
847                positioned("a", 0.0, 0.0, 100.0, 100.0),
848                positioned("b", 120.0, 0.0, 100.0, 100.0),
849            ],
850            vec![positioned("a", f64::NAN, 0.0, 100.0, 100.0)],
851            vec![positioned("a", 0.0, 0.0, -1.0, 100.0)],
852            vec![
853                positioned("a", 0.0, 0.0, 100.0, 100.0),
854                positioned("a", 104.0, 0.0, 100.0, 100.0),
855            ],
856        ] {
857            assert!(reconstruct(panes).is_err());
858        }
859        assert!(
860            reconstruct(vec![
861                positioned("a", 0.0, 0.0, 200.0, 100.0),
862                positioned("b", 200.0, 0.0, 100.0, 200.0),
863                positioned("c", 100.0, 200.0, 200.0, 100.0),
864                positioned("d", 0.0, 100.0, 100.0, 200.0),
865                positioned("e", 100.0, 100.0, 100.0, 100.0),
866            ])
867            .is_err()
868        );
869    }
870
871    #[test]
872    fn malformed_targets_ratios_and_action_injection_are_rejected() {
873        for ratio in [0.0, 1.0, -1.0, f64::NAN, f64::INFINITY, f64::MIN_POSITIVE] {
874            assert!(
875                state(split(Axis::Vertical, ratio, leaf("a"), leaf("b")))
876                    .validate()
877                    .is_err()
878            );
879        }
880        let mut saved = state(leaf("a"));
881        let PaneTree::Pane { pane: local } = &mut saved.tabs[0].root else {
882            panic!()
883        };
884        if let RecoveryTarget::LocalCodex { thread_id, .. } = &mut local.target {
885            *thread_id = "not-a-uuid".into();
886        }
887        assert!(saved.validate().is_err());
888        for host in ["-oProxyCommand=bad", "host name", "host;nt", "host\nother"] {
889            let mut p = pane("remote");
890            p.target = RecoveryTarget::RemoteTmux {
891                host: host.into(),
892                socket: "/tmp/tmux.sock".into(),
893                session: "session".into(),
894                remote_program: "agent-ssh".into(),
895            };
896            assert!(state(PaneTree::Pane { pane: p }).validate().is_err());
897        }
898        for field in 0..3 {
899            let mut p = pane("remote");
900            let mut values = [
901                "/tmp/tmux.sock".to_owned(),
902                "session".to_owned(),
903                "agent-ssh".to_owned(),
904            ];
905            values[field].push_str("; nt");
906            p.target = RecoveryTarget::RemoteTmux {
907                host: "pulse-admin".into(),
908                socket: values[0].clone(),
909                session: values[1].clone(),
910                remote_program: values[2].clone(),
911            };
912            assert!(state(PaneTree::Pane { pane: p }).validate().is_err());
913        }
914        assert!(state(leaf("a")).wt_args("new;nt", false).is_err());
915        assert!(
916            state(split(Axis::Vertical, 0.5, leaf("same"), leaf("same")))
917                .validate()
918                .is_err()
919        );
920        assert!(
921            SavedState::parse(r#"{"version":3,"tabs":[],"selected_tab":null,"unknown":true}"#)
922                .is_err()
923        );
924    }
925
926    #[test]
927    fn duplicate_local_conversations_and_false_readiness_are_rejected() {
928        let left = pane("left");
929        let mut right = left.clone();
930        right.key = "right".into();
931        let duplicate = state(split(
932            Axis::Vertical,
933            0.5,
934            PaneTree::Pane { pane: left },
935            PaneTree::Pane { pane: right },
936        ));
937        assert!(
938            duplicate
939                .validate()
940                .unwrap_err()
941                .to_string()
942                .contains("same local Codex conversation")
943        );
944        let mut incomplete = state(PaneTree::Pane {
945            pane: SavedPane {
946                key: "unknown".into(),
947                title: "unknown".into(),
948                target: RecoveryTarget::Unavailable {
949                    reason: "missing handle".into(),
950                },
951            },
952        });
953        assert!(incomplete.validate().is_err());
954        incomplete.restorable = false;
955        let round_trip = SavedState::parse(&serde_json::to_string(&incomplete).unwrap()).unwrap();
956        assert_eq!(round_trip.panes().len(), 1);
957        assert!(round_trip.wt_args("new", true).is_err());
958    }
959
960    #[test]
961    fn remote_attach_is_exact_and_session_cannot_be_an_option() {
962        let p = SavedPane {
963            key: "r".into(),
964            title: "remote".into(),
965            target: RecoveryTarget::RemoteTmux {
966                host: "pulse-admin".into(),
967                socket: "/tmp/private socket".into(),
968                session: "-literal".into(),
969                remote_program: "/opt/agent ssh".into(),
970            },
971        };
972        let args = state(PaneTree::Pane { pane: p })
973            .wt_args("new", false)
974            .unwrap();
975        assert!(args.windows(3).any(|a| a == ["attach", "--", "-literal"]));
976        assert!(
977            args.windows(2)
978                .any(|a| a == ["--socket", "/tmp/private socket"])
979        );
980        assert!(!args.iter().any(|a| a == "new-session"));
981    }
982
983    #[test]
984    fn write_new_never_replaces_recovery_copy() {
985        let path = std::env::temp_dir().join(format!(
986            "agent-ssh-snapshot-test-{}-{}.json",
987            std::process::id(),
988            std::time::SystemTime::now()
989                .duration_since(std::time::UNIX_EPOCH)
990                .unwrap()
991                .as_nanos()
992        ));
993        let saved = state(leaf("a"));
994        saved.write_new(&path).unwrap();
995        let original = fs::read(&path).unwrap();
996        assert!(state(leaf("b")).write_new(&path).is_err());
997        assert_eq!(fs::read(&path).unwrap(), original);
998        fs::remove_file(path).unwrap();
999    }
1000
1001    #[test]
1002    fn competing_writers_publish_only_one_snapshot() {
1003        let path = std::env::temp_dir().join(format!(
1004            "agent-ssh-snapshot-race-{}-{}.json",
1005            std::process::id(),
1006            std::time::SystemTime::now()
1007                .duration_since(std::time::UNIX_EPOCH)
1008                .unwrap()
1009                .as_nanos()
1010        ));
1011        let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
1012        let writers: Vec<_> = ["a", "b"]
1013            .into_iter()
1014            .map(|key| {
1015                let path = path.clone();
1016                let barrier = barrier.clone();
1017                std::thread::spawn(move || {
1018                    barrier.wait();
1019                    state(leaf(key)).write_new(&path).is_ok()
1020                })
1021            })
1022            .collect();
1023        assert_eq!(
1024            writers
1025                .into_iter()
1026                .map(|w| usize::from(w.join().unwrap()))
1027                .sum::<usize>(),
1028            1
1029        );
1030        let saved = SavedState::parse(&fs::read_to_string(&path).unwrap()).unwrap();
1031        assert!(matches!(saved.panes()[0].key.as_str(), "a" | "b"));
1032        fs::remove_file(path).unwrap();
1033    }
1034
1035    #[test]
1036    fn counts_depth_selection_and_command_size_are_bounded() {
1037        let mut saved = state(leaf("a"));
1038        saved.tabs[0].focused_pane = Some("missing".into());
1039        assert!(saved.validate().is_err());
1040        saved.tabs[0].focused_pane = Some("a".into());
1041        assert!(saved.validate().is_ok());
1042        let mut no_focus = state(leaf("a"));
1043        no_focus.tabs[0].focused_pane = None;
1044        let json = serde_json::to_string(&no_focus).unwrap();
1045        assert!(!json.contains("focused_pane"));
1046        assert!(
1047            SavedState::parse(&json).unwrap().tabs[0]
1048                .focused_pane
1049                .is_none()
1050        );
1051        saved.selected_tab = Some(1);
1052        assert!(saved.validate().is_err());
1053        saved.selected_tab = None;
1054        for i in 0..MAX_DEPTH + 1 {
1055            saved.tabs[0].root = split(
1056                Axis::Vertical,
1057                0.5,
1058                saved.tabs[0].root.clone(),
1059                leaf(&format!("p{i}")),
1060            );
1061        }
1062        assert!(saved.validate().is_err());
1063        let mut saved = state(leaf("a"));
1064        for i in 0..20 {
1065            saved.tabs.push(SavedTab {
1066                title: "t".into(),
1067                root: leaf(&format!("p{i}")),
1068                focused_pane: None,
1069            });
1070        }
1071        for tab in &mut saved.tabs {
1072            if let PaneTree::Pane { pane } = &mut tab.root {
1073                pane.title = "x".repeat(2000);
1074            }
1075        }
1076        assert!(saved.wt_args("new", true).is_err());
1077    }
1078}