1use crate::{
2 attachment::{
3 AttachmentReference, AttachmentResolution, CommandSpec, Observation, validate_text,
4 },
5 workspace::{Pane, Workspace},
6};
7use anyhow::{Context, Result, bail};
8use serde::{Deserialize, Serialize};
9use std::{fs, path::Path};
10
11#[derive(Clone, Debug, Serialize, Deserialize)]
12#[serde(deny_unknown_fields)]
13pub struct TerminalLayout {
14 pub version: u32,
15 pub panes_per_tab: usize,
16 pub panes: Vec<LayoutPane>,
17}
18
19#[derive(Clone, Debug, Serialize, Deserialize)]
20#[serde(deny_unknown_fields)]
21pub struct LayoutPane {
22 pub title: String,
23 #[serde(default, skip_serializing_if = "Option::is_none")]
24 pub cwd: Option<String>,
25 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub profile: Option<String>,
27 pub attachment: PaneAttachment,
28}
29
30#[derive(Clone, Debug, Serialize, Deserialize)]
31#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
32pub enum PaneAttachment {
33 ConfiguredCommand {
34 command: Vec<String>,
35 },
36 Resolved {
37 target: AttachmentReference,
38 resolver: CommandSpec,
39 },
40}
41
42#[derive(Debug, Serialize)]
43pub struct RestorePlan {
44 pub version: u32,
45 pub blocked: bool,
46 pub skipped: usize,
47 pub panes: Vec<PaneObservation>,
48 pub terminal_args: Vec<String>,
49}
50
51#[derive(Debug, Serialize)]
52pub struct PaneObservation {
53 pub title: String,
54 #[serde(skip_serializing_if = "Option::is_none")]
55 pub target: Option<AttachmentReference>,
56 pub state: String,
57 #[serde(skip_serializing_if = "Option::is_none")]
58 pub reason: Option<String>,
59}
60
61impl TerminalLayout {
62 pub fn read(path: &Path) -> Result<Self> {
63 let text = fs::read_to_string(path)
64 .with_context(|| format!("cannot read terminal layout {}", path.display()))?;
65 Self::parse(&text)
66 }
67
68 pub fn parse(text: &str) -> Result<Self> {
69 let value: serde_json::Value = serde_json::from_str(text.trim_start_matches('\u{feff}'))
70 .context("invalid terminal layout JSON")?;
71 let layout = match value.get("version").and_then(serde_json::Value::as_u64) {
72 Some(1) => Self::from_legacy(
73 serde_json::from_value(value).context("invalid version 1 layout")?,
74 )?,
75 Some(2) => {
76 serde_json::from_value(value).context("invalid version 2 terminal layout")?
77 }
78 _ => bail!("unsupported terminal layout version; expected 1 or 2"),
79 };
80 layout.validate()?;
81 Ok(layout)
82 }
83
84 pub fn from_legacy(workspace: Workspace) -> Result<Self> {
85 workspace.validate()?;
86 Ok(Self {
87 version: 2,
88 panes_per_tab: workspace.panes_per_tab,
89 panes: workspace
90 .panes
91 .into_iter()
92 .map(|pane| LayoutPane {
93 title: pane.title,
94 cwd: pane.cwd,
95 profile: pane.profile,
96 attachment: PaneAttachment::ConfiguredCommand {
97 command: pane.command,
98 },
99 })
100 .collect(),
101 })
102 }
103
104 pub fn validate(&self) -> Result<()> {
105 if self.version != 2 {
106 bail!("unsupported terminal layout version; expected 2");
107 }
108 if !(1..=16).contains(&self.panes_per_tab) {
109 bail!("panes per tab must be between 1 and 16");
110 }
111 if self.panes.is_empty() {
112 bail!("terminal layout contains no panes");
113 }
114 for pane in &self.panes {
115 for value in std::iter::once(&pane.title)
116 .chain(pane.cwd.iter())
117 .chain(pane.profile.iter())
118 {
119 validate_text(value)?;
120 }
121 match &pane.attachment {
122 PaneAttachment::ConfiguredCommand { command } => {
123 command_spec(command, pane.cwd.clone())?.validate()?;
124 }
125 PaneAttachment::Resolved { target, resolver } => {
126 target.validate()?;
127 resolver.validate()?;
128 }
129 }
130 }
131 Ok(())
132 }
133
134 pub fn write(&self, path: &Path) -> Result<()> {
135 use std::io::Write;
136 self.validate()?;
137 let bytes = serde_json::to_vec_pretty(self)?;
138 let mut file = fs::OpenOptions::new()
139 .write(true)
140 .create_new(true)
141 .open(path)
142 .with_context(|| {
143 format!(
144 "cannot create terminal layout {}; choose a new filename if it exists",
145 path.display()
146 )
147 })?;
148 file.write_all(&bytes)?;
149 file.write_all(b"\n")?;
150 Ok(())
151 }
152
153 pub fn plan(
155 &self,
156 window: &str,
157 panes_per_tab: Option<usize>,
158 allow_partial: bool,
159 mut resolve: impl FnMut(&CommandSpec) -> Result<AttachmentResolution>,
160 ) -> Result<RestorePlan> {
161 self.validate()?;
162 validate_text(window)?;
163 let count = panes_per_tab.unwrap_or(self.panes_per_tab);
164 if !(1..=16).contains(&count) {
165 bail!("panes per tab must be between 1 and 16");
166 }
167 let mut reports = Vec::new();
168 let mut ready = Vec::new();
169 for pane in &self.panes {
170 let (target, observation, command) = match &pane.attachment {
171 PaneAttachment::ConfiguredCommand { command } => {
172 (None, None, Some(command_spec(command, pane.cwd.clone())?))
173 }
174 PaneAttachment::Resolved { target, resolver } => {
175 let observation = match resolve(resolver).and_then(|reply| {
176 reply.validate_for(target)?;
177 Ok(reply.observation)
178 }) {
179 Ok(observation) => observation,
180 Err(_) => Observation::Uncertain {
181 reason: "resolver failed or returned an invalid or mismatched response"
182 .into(),
183 },
184 };
185 let command = match &observation {
186 Observation::Attachable { plan } => Some(plan.command()),
187 _ => None,
188 };
189 (Some(target.clone()), Some(observation), command)
190 }
191 };
192 reports.push(PaneObservation {
193 title: pane.title.clone(),
194 target,
195 state: observation
196 .as_ref()
197 .map_or("configured_command", Observation::state)
198 .into(),
199 reason: observation
200 .as_ref()
201 .and_then(Observation::reason)
202 .map(|reason| {
203 reason
204 .chars()
205 .filter(|c| !c.is_control())
206 .take(4096)
207 .collect()
208 }),
209 });
210 if let Some(command) = command {
211 let mut argv = vec![command.program];
212 argv.extend(command.args);
213 ready.push(Pane {
214 title: pane.title.clone(),
215 cwd: command.cwd.or_else(|| pane.cwd.clone()),
216 profile: pane.profile.clone(),
217 command: argv,
218 });
219 }
220 }
221 let skipped = self.panes.len() - ready.len();
222 let blocked = skipped > 0 && !allow_partial;
223 let terminal_args = if blocked || ready.is_empty() {
224 Vec::new()
225 } else {
226 Workspace {
227 version: 1,
228 panes_per_tab: count,
229 panes: ready,
230 }
231 .wt_args(window, None)?
232 };
233 Ok(RestorePlan {
234 version: 1,
235 blocked,
236 skipped,
237 panes: reports,
238 terminal_args,
239 })
240 }
241}
242
243fn command_spec(command: &[String], cwd: Option<String>) -> Result<CommandSpec> {
244 let Some((program, args)) = command.split_first() else {
245 bail!("configured pane needs a command");
246 };
247 Ok(CommandSpec {
248 program: program.clone(),
249 args: args.to_vec(),
250 cwd,
251 })
252}
253
254#[cfg(test)]
255mod tests {
256 use super::*;
257 fn target(id: &str) -> AttachmentReference {
258 AttachmentReference::Managed {
259 authority: "pulse-agents".into(),
260 origin: "https://agents.example".into(),
261 agent_id: id.into(),
262 }
263 }
264 fn layout() -> TerminalLayout {
265 TerminalLayout {
266 version: 2,
267 panes_per_tab: 4,
268 panes: vec![LayoutPane {
269 title: "agent".into(),
270 cwd: None,
271 profile: None,
272 attachment: PaneAttachment::Resolved {
273 target: target("a"),
274 resolver: CommandSpec {
275 program: "producer".into(),
276 args: vec![],
277 cwd: None,
278 },
279 },
280 }],
281 }
282 }
283 #[test]
284 fn every_non_ready_state_has_no_terminal_actions() {
285 for state in [
286 "resume_required",
287 "unreachable",
288 "ownership_conflict",
289 "uncertain",
290 "deleted",
291 "unsupported",
292 "unavailable",
293 ] {
294 let observation: Observation =
295 serde_json::from_value(serde_json::json!({"state":state,"reason":"not ready"}))
296 .unwrap();
297 let result = layout()
298 .plan("agents", None, false, |_| {
299 Ok(AttachmentResolution {
300 version: 1,
301 target: target("a"),
302 observation: observation.clone(),
303 })
304 })
305 .unwrap();
306 assert!(result.blocked);
307 assert!(result.terminal_args.is_empty());
308 assert_eq!(result.panes[0].state, state);
309 }
310 }
311 #[test]
312 fn a_different_target_is_not_attachable() {
313 let report = layout()
314 .plan("agents", None, false, |_| {
315 Ok(AttachmentResolution {
316 version: 1,
317 target: target("b"),
318 observation: Observation::Attachable {
319 plan: crate::attachment::AttachmentPlan::LocalProcess {
320 program: "wrong-agent".into(),
321 args: vec![],
322 cwd: None,
323 },
324 },
325 })
326 })
327 .unwrap();
328 assert!(report.blocked);
329 assert!(report.terminal_args.is_empty());
330 assert_eq!(report.panes[0].state, "uncertain");
331 }
332 #[test]
333 fn partial_mode_only_contains_ready_commands() {
334 let mut layout = layout();
335 layout.panes.push(LayoutPane {
336 title: "explicit".into(),
337 cwd: None,
338 profile: None,
339 attachment: PaneAttachment::ConfiguredCommand {
340 command: vec!["safe-agent".into()],
341 },
342 });
343 let report = layout
344 .plan("agents", None, true, |_| {
345 Ok(AttachmentResolution {
346 version: 1,
347 target: target("a"),
348 observation: Observation::Unavailable {
349 reason: "offline".into(),
350 },
351 })
352 })
353 .unwrap();
354 assert!(!report.blocked);
355 assert_eq!(report.skipped, 1);
356 assert!(report.terminal_args.contains(&"safe-agent".into()));
357 assert!(!report.terminal_args.contains(&"producer".into()));
358 }
359}