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