1use crate::host::{HostConfig, HostHandle, HostInfo, KeptShot};
7use serde::Serialize;
8use serde_json::{json, Value};
9use std::path::PathBuf;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::Mutex;
12
13pub struct Session {
14 pub id: String,
15 pub dir: PathBuf,
16 pub host: HostHandle,
17 pub config: Option<HostConfig>,
21 pub started_ms: f64,
23 shots: AtomicU64,
24 shot_bytes: Mutex<usize>,
25 recorder: Mutex<Recorder>,
26}
27
28#[derive(Default)]
29struct Recorder {
30 on: bool,
31 steps: Vec<Value>,
32 bytes: usize,
33}
34
35#[derive(Serialize)]
36pub struct SessionInfo {
37 pub id: String,
38 pub dir: String,
39 pub host: HostInfo,
40 pub uptime_ms: u128,
41 pub shots: u64,
42 pub recording: bool,
43}
44
45impl Session {
46 pub fn new(root: &std::path::Path, host: HostHandle, config: Option<HostConfig>, record: bool) -> Result<Self, String> {
47 let id = host.platform.stamp();
48 let dir = host.platform.session_dir(root, &id)?;
49 let started_ms = host.platform.now_ms();
50 Ok(Self {
51 id,
52 dir,
53 host,
54 config,
55 started_ms,
56 shots: AtomicU64::new(0),
57 shot_bytes: Mutex::new(0),
58 recorder: Mutex::new(Recorder { on: record, steps: Vec::new(), bytes: 0 }),
59 })
60 }
61
62 pub fn info(&self) -> SessionInfo {
63 SessionInfo {
64 id: self.id.clone(),
65 dir: self.dir.display().to_string(),
66 host: self.host.info.clone(),
67 uptime_ms: (self.host.platform.now_ms() - self.started_ms).max(0.0) as u128,
68 shots: self.shots.load(Ordering::Relaxed),
69 recording: self.recorder.lock().unwrap().on,
70 }
71 }
72
73 pub fn keep_shot(&self, png: &[u8], manifest: Option<&Value>) -> Result<(u64, KeptShot), String> {
77 let mut bytes = self.shot_bytes.lock().unwrap();
78 let manifest_bytes = manifest.map(serde_json::to_vec_pretty).transpose().map_err(|e| e.to_string())?.map_or(0, |v| v.len());
79 let size = png.len().saturating_add(manifest_bytes);
80 if self.shots.load(Ordering::Relaxed) >= 4096 || bytes.saturating_add(size) > 256 << 20 {
81 return Err("session screenshot storage is full (4096 captures or 256 MiB); retained captures are preserved".into());
82 }
83 let n = self.shots.fetch_add(1, Ordering::Relaxed) + 1;
84 *bytes += size;
86 let kept = self.host.platform.keep_shot(&self.dir, n, png, manifest)?;
87 Ok((n, kept))
88 }
89
90 pub fn record(&self, tool: &str, args: &Value, ok: bool, digest: Value) {
91 let mut r = self.recorder.lock().unwrap();
92 if !r.on {
93 return;
94 }
95 let entry = json!({ "tool": tool, "args": args, "ok": ok, "digest": digest });
96 let line = entry.to_string();
97 if r.steps.len() >= 4096 || r.bytes + line.len() > 16 << 20 {
98 r.on = false;
99 return;
100 }
101 r.bytes += line.len();
102 r.steps.push(entry);
103 self.host.platform.append_log(&self.dir, &line);
104 }
105
106 pub fn set_recording(&self, on: bool) {
107 self.recorder.lock().unwrap().on = on;
108 }
109
110 pub fn script(&self, name: &str, since: usize) -> Value {
112 let r = self.recorder.lock().unwrap();
113 let steps: Vec<Value> = r
114 .steps
115 .iter()
116 .skip(since)
117 .filter(|s| !matches!(s["tool"].as_str(), Some("session_script") | Some("session_info") | Some("session_record")))
118 .map(|s| json!({ "tool": s["tool"], "args": s["args"] }))
119 .collect();
120 json!({
121 "name": name,
122 "note": "recorded by session_script; add `expect` entries before committing",
123 "backend": self.host.info.backend,
124 "size": [self.host.info.width, self.host.info.height],
125 "ppp": self.host.info.ppp,
126 "steps": steps,
127 })
128 }
129}
130