use std::collections::{HashMap, HashSet};
use anyhow::{Context, Result, bail};
use serde::Deserialize;
use serde_json::Value;
use crate::capture::{
NativeCapture, NativeConnection, NativePane, NativeProcess, NativeRect, NativeTab,
};
#[derive(Deserialize)]
pub struct Observation {
hwnd: String,
records: Vec<Record>,
connections: Vec<NativeConnection>,
layout: Value,
age_seconds: f64,
}
#[derive(Deserialize)]
struct Record {
#[serde(flatten)]
process: NativeProcess,
session_id: String,
terminal_pid: u32,
}
fn session(value: &str) -> Result<String> {
let value = value.trim_matches(['{', '}']).to_ascii_lowercase();
if value.len() != 36
|| !value.bytes().enumerate().all(|(i, b)| {
if [8, 13, 18, 23].contains(&i) {
b == b'-'
} else {
b.is_ascii_hexdigit()
}
})
{
bail!("invalid native terminal session GUID");
}
Ok(value)
}
struct Leaf {
id: usize,
session: String,
title: String,
rect: NativeRect,
}
fn parse_tabs(actions: &[Value]) -> Result<(Vec<Vec<Leaf>>, Option<usize>)> {
let mut tabs: Vec<Vec<Leaf>> = Vec::new();
let mut active = 0;
let mut next_id = 1;
let mut selected = None;
for a in actions {
match a["action"].as_str().context("native action has no name")? {
"newTab" => {
if tabs.len() >= 64 {
bail!("native tab count exceeds bound");
}
tabs.push(vec![Leaf {
id: 0,
session: session(
a["sessionId"]
.as_str()
.context("native pane lacks session identity")?,
)?,
title: a["tabTitle"].as_str().unwrap_or("").into(),
rect: NativeRect {
x: 0.,
y: 0.,
width: 10000.,
height: 10000.,
},
}]);
active = 0;
next_id = 1;
selected = Some(tabs.len() - 1);
}
"splitPane" => {
let tab = tabs.last_mut().context("split before tab")?;
if tab.len() >= 64 {
bail!("native pane count exceeds bound");
}
let at = tab
.iter()
.position(|l| l.id == active)
.context("native focus references absent pane")?;
let size = a["size"]
.as_f64()
.context("native split has no explicit ratio")?;
if !size.is_finite() || !(0.001..=0.999).contains(&size) {
bail!("invalid native split ratio");
}
if a["splitMode"].as_str() != Some("manual") {
bail!("unsupported native split mode");
}
let old = &mut tab[at].rect;
let mut new = NativeRect {
x: old.x,
y: old.y,
width: old.width,
height: old.height,
};
match a["split"].as_str() {
Some("right") => {
old.width *= 1. - size;
new.x += old.width;
new.width *= size;
}
Some("down") => {
old.height *= 1. - size;
new.y += old.height;
new.height *= size;
}
_ => bail!("unsupported native split direction"),
}
tab.insert(
at + 1,
Leaf {
id: next_id,
session: session(
a["sessionId"]
.as_str()
.context("native split lacks session identity")?,
)?,
title: a["tabTitle"].as_str().unwrap_or("").into(),
rect: new,
},
);
active = next_id;
next_id += 1;
}
"moveFocus" => {
let tab = tabs.last().context("focus before tab")?;
let at = tab
.iter()
.position(|l| l.id == active)
.context("invalid native focus")?;
let next = match a["direction"].as_str() {
Some("previousInOrder") => (at + tab.len() - 1) % tab.len(),
Some("nextInOrder") => (at + 1) % tab.len(),
_ => bail!("unsupported native focus direction"),
};
active = tab[next].id;
}
"focusPane" => {
active = a["id"].as_u64().context("invalid native focus id")? as usize;
if !tabs
.last()
.is_some_and(|t| t.iter().any(|l| l.id == active))
{
bail!("native focus references absent pane");
}
}
"switchToTab" => {
let index = a["index"]
.as_u64()
.context("invalid native tab selection")? as usize;
if index >= tabs.len() {
bail!("invalid native tab selection");
}
selected = Some(index);
}
"renameWindow" => {}
name => bail!("unsupported native checkpoint action: {name}"),
}
}
if tabs.is_empty() {
bail!("native checkpoint contains no tabs");
}
Ok((tabs, selected))
}
pub fn collect(bytes: &[u8]) -> Result<NativeCapture> {
let observation: Observation =
serde_json::from_slice(bytes).context("invalid passive metadata response")?;
if !observation.age_seconds.is_finite() || !(0.0..=420.).contains(&observation.age_seconds) {
bail!(
"native layout checkpoint is stale; wait for Windows Terminal's next five-minute checkpoint"
);
}
let mut records: HashMap<String, Vec<Record>> = HashMap::new();
let mut terminal = None;
for record in observation.records {
if terminal.is_some_and(|pid| pid != record.terminal_pid) {
bail!("passive observation crosses terminal instances");
}
terminal = Some(record.terminal_pid);
records
.entry(session(&record.session_id)?)
.or_default()
.push(record);
}
let windows = observation.layout["persistedWindowLayouts"]
.as_array()
.context("native layout checkpoint is unavailable")?;
if windows.len() > 128 {
bail!("native window count exceeds bound");
}
let mut matches = Vec::new();
for w in windows {
let mut actions = w["tabLayout"]
.as_array()
.context("native window has no tab layout")?;
if actions.len() == 1 && actions[0]["action"] == "openWorkspace" {
let name = actions[0]["name"]
.as_str()
.context("native workspace reference has no name")?;
actions = observation.layout["persistedWorkspaces"][name]["tabLayout"]
.as_array()
.context("native workspace layout is missing")?;
}
if actions.len() > 2048 {
bail!("native action count exceeds bound");
}
if actions
.iter()
.filter_map(|a| a["sessionId"].as_str())
.filter_map(|s| session(s).ok())
.any(|s| records.contains_key(&s))
{
matches.push(actions);
}
}
if matches.len() != 1 {
bail!(
"checkpoint has no unique session binding to this live window; wait for its next checkpoint"
);
}
let (tabs, selected_tab) = parse_tabs(matches[0])?;
let expected: HashSet<_> = tabs.iter().flatten().map(|l| l.session.clone()).collect();
if expected.len() != tabs.iter().map(Vec::len).sum::<usize>() {
bail!("duplicate native pane session identity");
}
if records.keys().any(|s| !expected.contains(s)) {
bail!(
"live panes are newer than the native layout checkpoint; wait for its next checkpoint"
);
}
let mut processes = Vec::new();
let mut result = Vec::new();
for tab in tabs {
let title = tab[0].title.clone();
let mut panes = Vec::new();
for leaf in tab {
let mut candidates = records.remove(&leaf.session).context(
"checkpoint includes a closed or unbound pane; wait for its next checkpoint",
)?;
if candidates.iter().any(|r| {
matches!(
r.process
.executable
.rsplit(['/', '\\'])
.next()
.unwrap_or("")
.to_ascii_lowercase()
.as_str(),
"codex.exe" | "ssh.exe"
)
}) {
candidates.retain(|r| {
matches!(
r.process
.executable
.rsplit(['/', '\\'])
.next()
.unwrap_or("")
.to_ascii_lowercase()
.as_str(),
"codex.exe" | "ssh.exe"
)
});
}
if candidates.len() != 1 {
bail!("pane has multiple live recovery candidates; refusing to guess");
}
let process = candidates.remove(0).process;
panes.push(NativePane {
console_pid: process.pid,
console_start_ticks: process.start_ticks,
title: leaf.title,
rect: leaf.rect,
members: vec![process.pid],
});
processes.push(process);
}
result.push(NativeTab { title, panes });
}
let connections = observation
.connections
.into_iter()
.filter(|c| {
processes.iter().any(|p| {
p.pid == c.pid
&& p.executable
.rsplit(['/', '\\'])
.next()
.is_some_and(|n| n.eq_ignore_ascii_case("ssh.exe"))
})
})
.collect();
Ok(NativeCapture {
version: 1,
checkpoint_age_seconds: Some(observation.age_seconds.round() as u64),
hwnd: observation.hwnd,
selected_tab,
tabs: result,
processes,
connections,
})
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn nested_first_branch_keeps_geometry_and_native_focus_ids() {
let id = |n| format!("00000000-0000-0000-0000-{n:012}");
let actions = vec![
json!({"action":"newTab","sessionId":id(1)}),
json!({"action":"splitPane","sessionId":id(2),"splitMode":"manual","split":"right","size":0.4}),
json!({"action":"moveFocus","direction":"previousInOrder"}),
json!({"action":"splitPane","sessionId":id(3),"splitMode":"manual","split":"down","size":0.3}),
json!({"action":"moveFocus","direction":"nextInOrder"}),
json!({"action":"splitPane","sessionId":id(4),"splitMode":"manual","split":"down","size":0.6}),
json!({"action":"focusPane","id":2}),
];
let (tabs, _) = parse_tabs(&actions).unwrap();
let t = &tabs[0];
assert_eq!(t.iter().map(|l| l.id).collect::<Vec<_>>(), [0, 2, 1, 3]);
assert_eq!(t[0].rect.width, 6000.);
assert_eq!(t[1].rect.y, 7000.);
assert_eq!(t[2].rect.x, 6000.);
assert_eq!(t[3].rect.y, 4000.);
}
#[test]
fn refuses_unknown_actions_and_missing_session_ids() {
assert!(parse_tabs(&[json!({"action":"newTab"})]).is_err());
assert!(
parse_tabs(&[json!({"action":"executeCommandline","commandline":"ignored"})]).is_err()
);
}
fn observation() -> Value {
json!({"hwnd":"100","checkpoint_utc":"2026-11-22T09:00:00Z","age_seconds":5.0,
"records":[{"pid":12,"parent_pid":1,"start_ticks":504911232000000100u64,"executable":"C:\\codex.exe","argv":["C:\\codex.exe"],"session_id":"00000000-0000-0000-0000-000000000001","terminal_pid":20}],"connections":[],
"layout":{"persistedWindowLayouts":[{"tabLayout":[{"action":"newTab","sessionId":"{00000000-0000-0000-0000-000000000001}","tabTitle":"same title"}]}]}})
}
#[test]
fn exact_session_join_rejects_staleness_duplicates_and_unbound_panes() {
let mut value = observation();
let run = |v: &Value| collect(&serde_json::to_vec(v).unwrap());
let capture = run(&value).unwrap();
assert_eq!(capture.tabs[0].panes[0].console_pid, 12);
value["age_seconds"] = json!(421);
assert!(run(&value).is_err());
value = observation();
let duplicate = value["records"][0].clone();
value["records"].as_array_mut().unwrap().push(duplicate);
assert!(run(&value).is_err());
value = observation();
value["records"][0]["session_id"] = json!("00000000-0000-0000-0000-000000000002");
assert!(run(&value).is_err());
value = observation();
let second = value["layout"]["persistedWindowLayouts"][0].clone();
value["layout"]["persistedWindowLayouts"]
.as_array_mut()
.unwrap()
.push(second);
assert!(run(&value).is_err());
}
#[test]
fn preview_named_workspace_resolves_only_an_existing_single_level_layout() {
let mut value = observation();
let window = value["layout"]["persistedWindowLayouts"][0].clone();
value["layout"]["persistedWorkspaces"] = json!({"fixture":window});
value["layout"]["persistedWindowLayouts"] =
json!([{"tabLayout":[{"action":"openWorkspace","name":"fixture"}]}]);
assert!(collect(&serde_json::to_vec(&value).unwrap()).is_ok());
value["layout"]["persistedWindowLayouts"][0]["tabLayout"][0]["name"] = json!("missing");
assert!(collect(&serde_json::to_vec(&value).unwrap()).is_err());
value["layout"]["persistedWindowLayouts"][0]["tabLayout"][0]["name"] = json!("fixture");
value["layout"]["persistedWorkspaces"]["fixture"]["tabLayout"] =
json!([{"action":"openWorkspace","name":"fixture"}]);
assert!(collect(&serde_json::to_vec(&value).unwrap()).is_err());
}
}