use std::{collections::HashSet, fs, io::Write, path::Path};
use anyhow::{Context, Result, bail};
use base64::{Engine, engine::general_purpose::STANDARD};
use serde::{Deserialize, Serialize};
const MAX_PANES: usize = 256;
const MAX_DEPTH: usize = 32;
const EPS: f64 = 0.01;
const MAX_GAP: f64 = 8.0;
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SavedState {
pub version: u32,
pub restorable: bool,
pub tabs: Vec<SavedTab>,
pub selected_tab: Option<usize>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SavedTab {
pub title: String,
pub root: PaneTree,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub focused_pane: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum PaneTree {
Pane {
pane: SavedPane,
},
Split {
axis: Axis,
first_fraction: f64,
first: Box<PaneTree>,
second: Box<PaneTree>,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Axis {
Vertical,
Horizontal,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SavedPane {
pub key: String,
pub title: String,
pub target: RecoveryTarget,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum RecoveryTarget {
Unavailable {
reason: String,
},
FreshShell {
executable: String,
cwd: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
message: Option<String>,
},
LocalCodex {
executable: String,
thread_id: String,
cwd: String,
yolo: bool,
},
RemoteTmux {
host: String,
socket: String,
session: String,
remote_program: String,
},
RemoteCodex {
host: String,
reference: Box<RemoteCodexReference>,
},
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RemoteCodexReference {
pub thread_id: String,
pub cwd: String,
pub yolo: bool,
pub codex_program: String,
pub managed_program: String,
pub codex_home: String,
pub launcher_pid: u32,
pub launcher_start: u64,
pub state_file: String,
}
impl RemoteCodexReference {
pub fn validate(&self) -> Result<()> {
if !uuid(&self.thread_id) || self.launcher_pid == 0 || self.launcher_start == 0 {
bail!("invalid remote Codex identity");
}
for value in [
&self.cwd,
&self.codex_program,
&self.managed_program,
&self.codex_home,
&self.state_file,
] {
nonempty(value)?;
if !value.starts_with('/') {
bail!("remote Codex paths must be absolute");
}
}
Ok(())
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Rect {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
#[derive(Clone, Debug)]
pub struct PositionedPane {
pub rect: Rect,
pub pane: SavedPane,
}
fn text(value: &str) -> Result<()> {
crate::attachment::validate_text(value)?;
if value.len() > 8192 {
bail!("snapshot field exceeds size limit");
}
Ok(())
}
fn nonempty(value: &str) -> Result<()> {
text(value)?;
if value.trim().is_empty() {
bail!("snapshot identity or path is empty");
}
Ok(())
}
fn uuid(value: &str) -> bool {
value.len() == 36
&& value.bytes().enumerate().all(|(i, b)| {
if [8, 13, 18, 23].contains(&i) {
b == b'-'
} else {
b.is_ascii_hexdigit()
}
})
}
impl SavedPane {
fn validate(&self) -> Result<()> {
nonempty(&self.key)?;
text(&self.title)?;
self.target.validate()
}
}
impl RecoveryTarget {
pub fn validate(&self) -> Result<()> {
match self {
RecoveryTarget::RemoteCodex { host, reference } => {
nonempty(host)?;
if host.starts_with('-') || host.chars().any(char::is_whitespace) {
bail!("invalid SSH host");
}
reference.validate()?;
}
RecoveryTarget::Unavailable { reason } => {
if reason.trim().is_empty()
|| reason.len() > 8192
|| reason.chars().any(char::is_control)
{
bail!("invalid unavailable-target reason");
}
}
RecoveryTarget::FreshShell {
executable,
cwd,
message,
} => {
nonempty(executable)?;
nonempty(cwd)?;
if executable.starts_with('-') {
bail!("invalid fresh-shell executable");
}
if message
.as_ref()
.is_some_and(|s| s.len() > 8192 || s.chars().any(char::is_control))
{
bail!("invalid shell recovery notice");
}
}
RecoveryTarget::LocalCodex {
executable,
thread_id,
cwd,
..
} => {
nonempty(executable)?;
nonempty(cwd)?;
if executable.starts_with('-') || !uuid(thread_id) {
bail!("invalid local Codex executable or thread UUID");
}
}
RecoveryTarget::RemoteTmux {
host,
socket,
session,
remote_program,
} => {
for value in [host, socket, session, remote_program] {
nonempty(value)?;
}
if host.starts_with('-')
|| host.chars().any(char::is_whitespace)
|| remote_program.starts_with('-')
|| !socket.starts_with('/')
{
bail!("invalid SSH host, remote executable, or absolute tmux socket");
}
}
}
Ok(())
}
}
impl SavedPane {
fn args(&self) -> Vec<String> {
let mut args = vec!["--title".into(), self.title.clone()];
match &self.target {
RecoveryTarget::RemoteCodex { host, reference } => {
args.extend([
"agent-ssh".into(),
"codex-recover".into(),
"--on".into(),
host.clone(),
"--reference".into(),
serde_json::to_string(reference).expect("serializable recovery reference"),
]);
}
RecoveryTarget::Unavailable { .. } => {
unreachable!("restore preflight rejects unavailable panes")
}
RecoveryTarget::FreshShell {
executable,
cwd,
message,
} => {
args.extend(["-d".into(), cwd.clone(), executable.clone()]);
if let Some(message) = message {
let command = format!(
"Write-Host '{}' -ForegroundColor Yellow",
message.replace('\'', "''")
);
let bytes = command
.encode_utf16()
.flat_map(u16::to_le_bytes)
.collect::<Vec<_>>();
args.extend([
"-NoLogo".into(),
"-NoProfile".into(),
"-NoExit".into(),
"-EncodedCommand".into(),
STANDARD.encode(bytes),
]);
}
}
RecoveryTarget::LocalCodex {
executable,
thread_id,
cwd,
yolo,
} => {
args.extend([
"-d".into(),
cwd.clone(),
executable.clone(),
"resume".into(),
]);
if *yolo {
args.push("--dangerously-bypass-approvals-and-sandbox".into());
}
args.push(thread_id.clone());
args.extend(["--cd".into(), cwd.clone()]);
}
RecoveryTarget::RemoteTmux {
host,
socket,
session,
remote_program,
} => {
args.extend([
"agent-ssh".into(),
"tmux".into(),
"--on".into(),
host.clone(),
"--socket".into(),
socket.clone(),
"--remote-program".into(),
remote_program.clone(),
"attach".into(),
"--".into(),
session.clone(),
]);
}
}
args
}
}
impl PaneTree {
fn visit<'a>(&'a self, out: &mut Vec<&'a SavedPane>) {
match self {
Self::Pane { pane } => out.push(pane),
Self::Split { first, second, .. } => {
first.visit(out);
second.visit(out);
}
}
}
fn validate(&self, depth: usize, count: &mut usize, keys: &mut HashSet<String>) -> Result<()> {
if depth > MAX_DEPTH {
bail!("snapshot split tree exceeds depth limit");
}
match self {
Self::Pane { pane } => {
*count += 1;
if *count > MAX_PANES {
bail!("snapshot exceeds pane limit");
}
pane.validate()?;
if !keys.insert(pane.key.clone()) {
bail!("duplicate snapshot pane key");
}
}
Self::Split {
first_fraction,
first,
second,
..
} => {
let second_fraction = 1.0 - first_fraction;
if !(*first_fraction > 0.0
&& *first_fraction < 1.0
&& second_fraction > 0.0
&& second_fraction < 1.0)
{
bail!("split fraction must be finite and strictly between zero and one");
}
first.validate(depth + 1, count, keys)?;
second.validate(depth + 1, count, keys)?;
}
}
Ok(())
}
fn first(&self) -> &SavedPane {
match self {
Self::Pane { pane } => pane,
Self::Split { first, .. } => first.first(),
}
}
fn compile(&self, args: &mut Vec<String>) {
if let Self::Split {
axis,
first_fraction,
first,
second,
} = self
{
let mut split = vec![
"sp".into(),
if *axis == Axis::Vertical { "-V" } else { "-H" }.into(),
"--size".into(),
(1.0 - first_fraction).to_string(),
];
split.extend(second.first().args());
action(args, split);
action(
args,
[
"mf".into(),
if *axis == Axis::Vertical {
"left"
} else {
"up"
}
.into(),
],
);
first.compile(args);
action(
args,
[
"mf".into(),
if *axis == Axis::Vertical {
"right"
} else {
"down"
}
.into(),
],
);
second.compile(args);
}
}
}
fn action(args: &mut Vec<String>, values: impl IntoIterator<Item = String>) {
if args.len() > 2 {
args.push(";".into());
}
args.extend(values);
}
impl SavedState {
pub fn parse(input: &str) -> Result<Self> {
if input.len() > 2 * 1024 * 1024 {
bail!("snapshot exceeds size limit");
}
let state: Self = serde_json::from_str(input.trim_start_matches('\u{feff}'))
.context("invalid version 3 snapshot JSON")?;
state.validate()?;
Ok(state)
}
pub fn validate(&self) -> Result<()> {
if self.version != 3 {
bail!("unsupported snapshot version; expected 3");
}
if self.tabs.is_empty() || self.tabs.len() > 64 {
bail!("snapshot needs 1 to 64 tabs");
}
if self.selected_tab.is_some_and(|i| i >= self.tabs.len()) {
bail!("selected tab is outside snapshot");
}
if self.restorable
== self
.panes()
.iter()
.any(|pane| matches!(pane.target, RecoveryTarget::Unavailable { .. }))
{
bail!("snapshot recovery status does not match its targets");
}
let mut count = 0;
let mut keys = HashSet::new();
let mut local_threads = HashSet::new();
let mut remote_threads = HashSet::new();
for tab in &self.tabs {
text(&tab.title)?;
tab.root.validate(0, &mut count, &mut keys)?;
if let Some(focused) = &tab.focused_pane {
let mut panes = Vec::new();
tab.root.visit(&mut panes);
if !panes.iter().any(|pane| &pane.key == focused) {
bail!("focused pane is outside its saved tab");
}
}
}
for pane in self.panes() {
if let RecoveryTarget::RemoteCodex { host, reference } = &pane.target
&& !remote_threads.insert((
host,
&reference.codex_home,
reference.thread_id.to_ascii_lowercase(),
))
{
bail!("multiple remote panes claim the same direct Codex conversation");
}
if let RecoveryTarget::LocalCodex { thread_id, .. } = &pane.target
&& !local_threads.insert(thread_id.to_ascii_lowercase())
{
bail!("multiple panes claim the same local Codex conversation");
}
}
Ok(())
}
pub fn write_new(&self, path: &Path) -> Result<()> {
self.validate()?;
let mut bytes = serde_json::to_vec_pretty(self)?;
bytes.push(b'\n');
if bytes.len() > 2 * 1024 * 1024 {
bail!("snapshot exceeds size limit");
}
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.with_context(|| {
format!(
"cannot create snapshot {}; choose a new filename",
path.display()
)
})?;
file.write_all(&bytes)?;
file.sync_all()?;
Ok(())
}
pub fn panes(&self) -> Vec<&SavedPane> {
let mut out = Vec::new();
for tab in &self.tabs {
tab.root.visit(&mut out);
}
out
}
pub fn panes_mut(&mut self) -> Vec<&mut SavedPane> {
fn visit<'a>(tree: &'a mut PaneTree, out: &mut Vec<&'a mut SavedPane>) {
match tree {
PaneTree::Pane { pane } => out.push(pane),
PaneTree::Split { first, second, .. } => {
visit(first, out);
visit(second, out);
}
}
}
let mut out = Vec::new();
for tab in &mut self.tabs {
visit(&mut tab.root, &mut out);
}
out
}
pub fn wt_args(&self, window: &str, include_focus: bool) -> Result<Vec<String>> {
self.validate()?;
if !self.restorable {
bail!("snapshot contains unavailable recovery targets");
}
nonempty(window)?;
let mut args = vec!["-w".into(), window.into()];
for tab in &self.tabs {
let mut new = vec!["nt".into()];
new.extend(tab.root.first().args());
action(&mut args, new);
tab.root.compile(&mut args);
action(&mut args, ["mf".into(), "first".into()]);
if let Some(key) = &tab.focused_pane {
let mut panes = Vec::new();
tab.root.visit(&mut panes);
let ordinal = panes.iter().position(|pane| &pane.key == key).unwrap();
for _ in 0..ordinal {
action(&mut args, ["mf".into(), "nextInOrder".into()]);
}
}
}
if include_focus && let Some(index) = self.selected_tab {
action(&mut args, ["ft".into(), "-t".into(), index.to_string()]);
}
let units: usize = args.iter().map(|s| s.encode_utf16().count() * 2 + 3).sum();
if units > 30_000 {
bail!("snapshot exceeds safe Windows command-line length");
}
Ok(args)
}
}
impl Rect {
fn end(self, axis: Axis) -> f64 {
self.start(axis) + self.size(axis)
}
fn start(self, axis: Axis) -> f64 {
if axis == Axis::Vertical {
self.x
} else {
self.y
}
}
fn size(self, axis: Axis) -> f64 {
if axis == Axis::Vertical {
self.width
} else {
self.height
}
}
fn valid(self) -> bool {
[
self.x,
self.y,
self.width,
self.height,
self.x + self.width,
self.y + self.height,
]
.iter()
.all(|v| v.is_finite() && v.abs() <= 1_000_000.0)
&& self.width > EPS
&& self.height > EPS
}
}
fn bounds(panes: &[PositionedPane]) -> Rect {
let x = panes.iter().map(|p| p.rect.x).fold(f64::INFINITY, f64::min);
let y = panes.iter().map(|p| p.rect.y).fold(f64::INFINITY, f64::min);
let right = panes
.iter()
.map(|p| p.rect.x + p.rect.width)
.fold(f64::NEG_INFINITY, f64::max);
let bottom = panes
.iter()
.map(|p| p.rect.y + p.rect.height)
.fold(f64::NEG_INFINITY, f64::max);
Rect {
x,
y,
width: right - x,
height: bottom - y,
}
}
pub fn reconstruct(panes: Vec<PositionedPane>) -> Result<PaneTree> {
if panes.is_empty() || panes.len() > MAX_PANES {
bail!("geometry needs 1 to 256 panes");
}
let mut keys = HashSet::new();
for (i, pane) in panes.iter().enumerate() {
pane.pane.validate()?;
if !pane.rect.valid() || !keys.insert(&pane.pane.key) {
bail!("invalid rectangle or duplicate pane key");
}
for other in &panes[..i] {
let a = pane.rect;
let b = other.rect;
if a.x.max(b.x) < (a.x + a.width).min(b.x + b.width) - EPS
&& a.y.max(b.y) < (a.y + a.height).min(b.y + b.height) - EPS
{
bail!("pane rectangles overlap");
}
}
}
reconstruct_inner(panes, 0, &mut 4096)
}
fn reconstruct_inner(
panes: Vec<PositionedPane>,
depth: usize,
budget: &mut usize,
) -> Result<PaneTree> {
if *budget == 0 {
bail!("geometry reconstruction exceeds work limit");
}
*budget -= 1;
if depth > MAX_DEPTH {
bail!("geometry exceeds split depth limit");
}
if panes.len() == 1 {
return Ok(PaneTree::Pane {
pane: panes.into_iter().next().unwrap().pane,
});
}
let parent = bounds(&panes);
for axis in [Axis::Vertical, Axis::Horizontal] {
let cross = if axis == Axis::Vertical {
Axis::Horizontal
} else {
Axis::Vertical
};
let mut cuts: Vec<f64> = panes.iter().map(|p| p.rect.end(axis)).collect();
cuts.sort_by(f64::total_cmp);
cuts.dedup_by(|a, b| (*a - *b).abs() < EPS);
for cut in cuts {
let (first, second): (Vec<_>, Vec<_>) = panes
.iter()
.cloned()
.partition(|p| p.rect.end(axis) <= cut + EPS);
if first.is_empty() || second.is_empty() {
continue;
}
let a = bounds(&first);
let b = bounds(&second);
let gap = b.start(axis) - a.end(axis);
if !(-EPS..=MAX_GAP).contains(&gap)
|| second.iter().any(|p| p.rect.start(axis) < cut - EPS)
|| (a.start(cross) - parent.start(cross)).abs() > EPS
|| (b.start(cross) - parent.start(cross)).abs() > EPS
|| (a.end(cross) - parent.end(cross)).abs() > EPS
|| (b.end(cross) - parent.end(cross)).abs() > EPS
{
continue;
}
if let (Ok(first), Ok(second)) = (
reconstruct_inner(first, depth + 1, budget),
reconstruct_inner(second, depth + 1, budget),
) {
return Ok(PaneTree::Split {
axis,
first_fraction: (a.end(axis) + gap / 2.0 - parent.start(axis))
/ parent.size(axis),
first: Box::new(first),
second: Box::new(second),
});
}
}
}
bail!("incomplete or non-guillotine pane geometry")
}
#[cfg(test)]
mod tests {
use super::*;
fn pane(key: &str) -> SavedPane {
SavedPane {
key: key.into(),
title: key.into(),
target: RecoveryTarget::LocalCodex {
executable: "C:\\Program Files\\Codex\\codex.exe".into(),
thread_id: format!(
"019aaaaa-1234-7890-abcd-{:012x}",
key.bytes()
.fold(0u64, |n, b| (n * 31 + u64::from(b)) & 0xffff_ffff_ffff)
),
cwd: "C:\\Work Projects".into(),
yolo: false,
},
}
}
fn leaf(key: &str) -> PaneTree {
PaneTree::Pane { pane: pane(key) }
}
fn split(axis: Axis, fraction: f64, first: PaneTree, second: PaneTree) -> PaneTree {
PaneTree::Split {
axis,
first_fraction: fraction,
first: Box::new(first),
second: Box::new(second),
}
}
fn state(root: PaneTree) -> SavedState {
SavedState {
version: 3,
restorable: true,
tabs: vec![SavedTab {
title: "work".into(),
root,
focused_pane: None,
}],
selected_tab: Some(0),
}
}
fn positioned(key: &str, x: f64, y: f64, width: f64, height: f64) -> PositionedPane {
PositionedPane {
pane: pane(key),
rect: Rect {
x,
y,
width,
height,
},
}
}
#[test]
fn asymmetric_tabs_compile_membership_ratios_and_directional_focus() {
let mut saved = state(split(
Axis::Vertical,
0.4,
split(Axis::Horizontal, 0.6, leaf("a"), leaf("b")),
split(Axis::Horizontal, 0.25, leaf("c"), leaf("d")),
));
saved.tabs.push(SavedTab {
title: "second".into(),
root: split(Axis::Vertical, 0.7, leaf("e"), leaf("f")),
focused_pane: Some("f".into()),
});
saved.selected_tab = Some(1);
let args = saved.wt_args("new", true).unwrap();
let actions: Vec<_> = args[2..].split(|s| s == ";").collect();
assert_eq!(actions.iter().filter(|a| a[0] == "nt").count(), 2);
let splits: Vec<_> = actions.iter().filter(|a| a[0] == "sp").collect();
assert_eq!(splits.len(), 4);
for (a, (axis, fraction)) in
splits
.iter()
.zip([("-V", 0.6), ("-H", 0.4), ("-H", 0.75), ("-V", 0.3)])
{
assert_eq!(a[1], axis);
assert!((a[3].parse::<f64>().unwrap() - fraction).abs() < 1e-10);
}
let focuses: Vec<_> = actions
.iter()
.filter(|a| a[0] == "mf")
.map(|a| a[1].as_str())
.collect();
assert_eq!(
focuses,
[
"left",
"up",
"down",
"right",
"up",
"down",
"first",
"left",
"right",
"first",
"nextInOrder"
]
);
assert!(!args.iter().any(|arg| arg == "fp" || arg == "focus-pane"));
assert_eq!(actions.last().unwrap(), &["ft", "-t", "1"]);
assert!(
!saved
.wt_args("append", false)
.unwrap()
.iter()
.any(|s| s == "ft")
);
assert_eq!(
saved
.panes()
.iter()
.map(|p| p.key.as_str())
.collect::<Vec<_>>(),
["a", "b", "c", "d", "e", "f"]
);
}
#[test]
fn six_pane_asymmetric_tree_crosses_only_unsplit_sibling_regions() {
let saved = state(split(
Axis::Vertical,
0.25,
split(Axis::Horizontal, 0.5, leaf("a"), leaf("b")),
split(
Axis::Vertical,
1.0 / 3.0,
split(Axis::Horizontal, 0.5, leaf("c"), leaf("d")),
split(Axis::Horizontal, 0.5, leaf("e"), leaf("f")),
),
));
let args = saved.wt_args("new", false).unwrap();
let actions: Vec<Vec<String>> = args[2..]
.split(|arg| arg == ";")
.map(|a| match a[0].as_str() {
"nt" => vec!["nt".into(), a[2].clone()],
"sp" => vec!["sp".into(), a[1].clone(), a[5].clone()],
"mf" => vec!["mf".into(), a[1].clone()],
_ => panic!("unexpected action"),
})
.collect();
let expected: Vec<Vec<String>> = [
vec!["nt", "a"],
vec!["sp", "-V", "c"],
vec!["mf", "left"],
vec!["sp", "-H", "b"],
vec!["mf", "up"],
vec!["mf", "down"],
vec!["mf", "right"],
vec!["sp", "-V", "e"],
vec!["mf", "left"],
vec!["sp", "-H", "d"],
vec!["mf", "up"],
vec!["mf", "down"],
vec!["mf", "right"],
vec!["sp", "-H", "f"],
vec!["mf", "up"],
vec!["mf", "down"],
vec!["mf", "first"],
]
.into_iter()
.map(|a| a.into_iter().map(str::to_owned).collect())
.collect();
assert_eq!(actions, expected);
}
#[test]
fn rectangle_grid_reconstructs_canonical_equivalent_geometry() {
let tree = reconstruct(vec![
positioned("d", 604.0, 304.0, 396.0, 496.0),
positioned("b", 0.0, 504.0, 600.0, 296.0),
positioned("a", 0.0, 0.0, 600.0, 500.0),
positioned("c", 604.0, 0.0, 396.0, 300.0),
])
.unwrap();
let PaneTree::Split {
axis,
first_fraction,
first,
second,
} = &tree
else {
panic!()
};
assert_eq!(*axis, Axis::Vertical);
assert!((*first_fraction - 0.602).abs() < 1e-10);
assert!(matches!(
first.as_ref(),
PaneTree::Split {
axis: Axis::Horizontal,
..
}
));
assert!(matches!(
second.as_ref(),
PaneTree::Split {
axis: Axis::Horizontal,
..
}
));
let saved = state(tree);
let roundtrip = SavedState::parse(&serde_json::to_string(&saved).unwrap()).unwrap();
assert_eq!(
roundtrip
.panes()
.iter()
.map(|p| p.key.as_str())
.collect::<Vec<_>>(),
["a", "b", "c", "d"]
);
let symmetric = reconstruct(vec![
positioned("a", 0.0, 0.0, 100.0, 100.0),
positioned("b", 0.0, 104.0, 100.0, 100.0),
positioned("c", 104.0, 0.0, 100.0, 100.0),
positioned("d", 104.0, 104.0, 100.0, 100.0),
])
.unwrap();
assert!(matches!(
symmetric,
PaneTree::Split {
axis: Axis::Vertical,
..
}
));
}
#[test]
fn malformed_geometry_is_rejected() {
for panes in [
vec![],
vec![
positioned("a", 0.0, 0.0, 100.0, 100.0),
positioned("b", 50.0, 50.0, 100.0, 100.0),
],
vec![
positioned("a", 0.0, 0.0, 100.0, 100.0),
positioned("b", 104.0, 0.0, 100.0, 50.0),
],
vec![
positioned("a", 0.0, 0.0, 100.0, 100.0),
positioned("b", 120.0, 0.0, 100.0, 100.0),
],
vec![positioned("a", f64::NAN, 0.0, 100.0, 100.0)],
vec![positioned("a", 0.0, 0.0, -1.0, 100.0)],
vec![
positioned("a", 0.0, 0.0, 100.0, 100.0),
positioned("a", 104.0, 0.0, 100.0, 100.0),
],
] {
assert!(reconstruct(panes).is_err());
}
assert!(
reconstruct(vec![
positioned("a", 0.0, 0.0, 200.0, 100.0),
positioned("b", 200.0, 0.0, 100.0, 200.0),
positioned("c", 100.0, 200.0, 200.0, 100.0),
positioned("d", 0.0, 100.0, 100.0, 200.0),
positioned("e", 100.0, 100.0, 100.0, 100.0),
])
.is_err()
);
}
#[test]
fn malformed_targets_ratios_and_action_injection_are_rejected() {
for ratio in [0.0, 1.0, -1.0, f64::NAN, f64::INFINITY, f64::MIN_POSITIVE] {
assert!(
state(split(Axis::Vertical, ratio, leaf("a"), leaf("b")))
.validate()
.is_err()
);
}
let mut saved = state(leaf("a"));
let PaneTree::Pane { pane: local } = &mut saved.tabs[0].root else {
panic!()
};
if let RecoveryTarget::LocalCodex { thread_id, .. } = &mut local.target {
*thread_id = "not-a-uuid".into();
}
assert!(saved.validate().is_err());
for host in ["-oProxyCommand=bad", "host name", "host;nt", "host\nother"] {
let mut p = pane("remote");
p.target = RecoveryTarget::RemoteTmux {
host: host.into(),
socket: "/tmp/tmux.sock".into(),
session: "session".into(),
remote_program: "agent-ssh".into(),
};
assert!(state(PaneTree::Pane { pane: p }).validate().is_err());
}
for field in 0..3 {
let mut p = pane("remote");
let mut values = [
"/tmp/tmux.sock".to_owned(),
"session".to_owned(),
"agent-ssh".to_owned(),
];
values[field].push_str("; nt");
p.target = RecoveryTarget::RemoteTmux {
host: "pulse-admin".into(),
socket: values[0].clone(),
session: values[1].clone(),
remote_program: values[2].clone(),
};
assert!(state(PaneTree::Pane { pane: p }).validate().is_err());
}
assert!(state(leaf("a")).wt_args("new;nt", false).is_err());
assert!(
state(split(Axis::Vertical, 0.5, leaf("same"), leaf("same")))
.validate()
.is_err()
);
assert!(
SavedState::parse(r#"{"version":3,"tabs":[],"selected_tab":null,"unknown":true}"#)
.is_err()
);
}
#[test]
fn duplicate_local_conversations_and_false_readiness_are_rejected() {
let left = pane("left");
let mut right = left.clone();
right.key = "right".into();
let duplicate = state(split(
Axis::Vertical,
0.5,
PaneTree::Pane { pane: left },
PaneTree::Pane { pane: right },
));
assert!(
duplicate
.validate()
.unwrap_err()
.to_string()
.contains("same local Codex conversation")
);
let mut incomplete = state(PaneTree::Pane {
pane: SavedPane {
key: "unknown".into(),
title: "unknown".into(),
target: RecoveryTarget::Unavailable {
reason: "missing handle".into(),
},
},
});
assert!(incomplete.validate().is_err());
incomplete.restorable = false;
let round_trip = SavedState::parse(&serde_json::to_string(&incomplete).unwrap()).unwrap();
assert_eq!(round_trip.panes().len(), 1);
assert!(round_trip.wt_args("new", true).is_err());
}
#[test]
fn remote_attach_is_exact_and_session_cannot_be_an_option() {
let p = SavedPane {
key: "r".into(),
title: "remote".into(),
target: RecoveryTarget::RemoteTmux {
host: "pulse-admin".into(),
socket: "/tmp/private socket".into(),
session: "-literal".into(),
remote_program: "/opt/agent ssh".into(),
},
};
let args = state(PaneTree::Pane { pane: p })
.wt_args("new", false)
.unwrap();
assert!(args.windows(3).any(|a| a == ["attach", "--", "-literal"]));
assert!(
args.windows(2)
.any(|a| a == ["--socket", "/tmp/private socket"])
);
assert!(!args.iter().any(|a| a == "new-session"));
}
#[test]
fn write_new_never_replaces_recovery_copy() {
let path = std::env::temp_dir().join(format!(
"agent-ssh-snapshot-test-{}-{}.json",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let saved = state(leaf("a"));
saved.write_new(&path).unwrap();
let original = fs::read(&path).unwrap();
assert!(state(leaf("b")).write_new(&path).is_err());
assert_eq!(fs::read(&path).unwrap(), original);
fs::remove_file(path).unwrap();
}
#[test]
fn competing_writers_publish_only_one_snapshot() {
let path = std::env::temp_dir().join(format!(
"agent-ssh-snapshot-race-{}-{}.json",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let barrier = std::sync::Arc::new(std::sync::Barrier::new(2));
let writers: Vec<_> = ["a", "b"]
.into_iter()
.map(|key| {
let path = path.clone();
let barrier = barrier.clone();
std::thread::spawn(move || {
barrier.wait();
state(leaf(key)).write_new(&path).is_ok()
})
})
.collect();
assert_eq!(
writers
.into_iter()
.map(|w| usize::from(w.join().unwrap()))
.sum::<usize>(),
1
);
let saved = SavedState::parse(&fs::read_to_string(&path).unwrap()).unwrap();
assert!(matches!(saved.panes()[0].key.as_str(), "a" | "b"));
fs::remove_file(path).unwrap();
}
#[test]
fn counts_depth_selection_and_command_size_are_bounded() {
let mut saved = state(leaf("a"));
saved.tabs[0].focused_pane = Some("missing".into());
assert!(saved.validate().is_err());
saved.tabs[0].focused_pane = Some("a".into());
assert!(saved.validate().is_ok());
let mut no_focus = state(leaf("a"));
no_focus.tabs[0].focused_pane = None;
let json = serde_json::to_string(&no_focus).unwrap();
assert!(!json.contains("focused_pane"));
assert!(
SavedState::parse(&json).unwrap().tabs[0]
.focused_pane
.is_none()
);
saved.selected_tab = Some(1);
assert!(saved.validate().is_err());
saved.selected_tab = None;
for i in 0..MAX_DEPTH + 1 {
saved.tabs[0].root = split(
Axis::Vertical,
0.5,
saved.tabs[0].root.clone(),
leaf(&format!("p{i}")),
);
}
assert!(saved.validate().is_err());
let mut saved = state(leaf("a"));
for i in 0..20 {
saved.tabs.push(SavedTab {
title: "t".into(),
root: leaf(&format!("p{i}")),
focused_pane: None,
});
}
for tab in &mut saved.tabs {
if let PaneTree::Pane { pane } = &mut tab.root {
pane.title = "x".repeat(2000);
}
}
assert!(saved.wt_args("new", true).is_err());
}
}