use crate::host::{HostConfig, HostHandle, HostInfo, KeptShot};
use serde::Serialize;
use serde_json::{json, Value};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
pub struct Session {
pub id: String,
pub dir: PathBuf,
pub host: HostHandle,
pub config: Option<HostConfig>,
pub started_ms: f64,
shots: AtomicU64,
shot_bytes: Mutex<usize>,
recorder: Mutex<Recorder>,
}
#[derive(Default)]
struct Recorder {
on: bool,
steps: Vec<Value>,
bytes: usize,
}
#[derive(Serialize)]
pub struct SessionInfo {
pub id: String,
pub dir: String,
pub host: HostInfo,
pub uptime_ms: u128,
pub shots: u64,
pub recording: bool,
}
impl Session {
pub fn new(root: &std::path::Path, host: HostHandle, config: Option<HostConfig>, record: bool) -> Result<Self, String> {
let id = host.platform.stamp();
let dir = host.platform.session_dir(root, &id)?;
let started_ms = host.platform.now_ms();
Ok(Self {
id,
dir,
host,
config,
started_ms,
shots: AtomicU64::new(0),
shot_bytes: Mutex::new(0),
recorder: Mutex::new(Recorder { on: record, steps: Vec::new(), bytes: 0 }),
})
}
pub fn info(&self) -> SessionInfo {
SessionInfo {
id: self.id.clone(),
dir: self.dir.display().to_string(),
host: self.host.info.clone(),
uptime_ms: (self.host.platform.now_ms() - self.started_ms).max(0.0) as u128,
shots: self.shots.load(Ordering::Relaxed),
recording: self.recorder.lock().unwrap().on,
}
}
pub fn keep_shot(&self, png: &[u8], manifest: Option<&Value>) -> Result<(u64, KeptShot), String> {
let mut bytes = self.shot_bytes.lock().unwrap();
let manifest_bytes = manifest.map(serde_json::to_vec_pretty).transpose().map_err(|e| e.to_string())?.map_or(0, |v| v.len());
let size = png.len().saturating_add(manifest_bytes);
if self.shots.load(Ordering::Relaxed) >= 4096 || bytes.saturating_add(size) > 256 << 20 {
return Err("session screenshot storage is full (4096 captures or 256 MiB); retained captures are preserved".into());
}
let n = self.shots.fetch_add(1, Ordering::Relaxed) + 1;
*bytes += size;
let kept = self.host.platform.keep_shot(&self.dir, n, png, manifest)?;
Ok((n, kept))
}
pub fn record(&self, tool: &str, args: &Value, ok: bool, digest: Value) {
let mut r = self.recorder.lock().unwrap();
if !r.on {
return;
}
let entry = json!({ "tool": tool, "args": args, "ok": ok, "digest": digest });
let line = entry.to_string();
if r.steps.len() >= 4096 || r.bytes + line.len() > 16 << 20 {
r.on = false;
return;
}
r.bytes += line.len();
r.steps.push(entry);
self.host.platform.append_log(&self.dir, &line);
}
pub fn set_recording(&self, on: bool) {
self.recorder.lock().unwrap().on = on;
}
pub fn script(&self, name: &str, since: usize) -> Value {
let r = self.recorder.lock().unwrap();
let steps: Vec<Value> = r
.steps
.iter()
.skip(since)
.filter(|s| !matches!(s["tool"].as_str(), Some("session_script") | Some("session_info") | Some("session_record")))
.map(|s| json!({ "tool": s["tool"], "args": s["args"] }))
.collect();
json!({
"name": name,
"note": "recorded by session_script; add `expect` entries before committing",
"backend": self.host.info.backend,
"size": [self.host.info.width, self.host.info.height],
"ppp": self.host.info.ppp,
"steps": steps,
})
}
}