Skip to main content

agent_ssh/
snapshot.rs

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