use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use async_trait::async_trait;
use serde_json::json;
use super::path::PathAccess;
use crate::hyperframes::{Finding, Format, LintReport, Quality, RenderRequest, Rendered};
use crate::{Tool, Workspace};
const ALL: [&str; 4] = ["instructions", "reference", "render", "inspect"];
const TOPICS: [&str; 3] = ["authoring", "rendering", "troubleshooting"];
const RESOLUTIONS: [&str; 6] = [
"landscape",
"portrait",
"square",
"landscape-4k",
"portrait-4k",
"square-4k",
];
const FPS_RULE: &str = "an integer 1-240 or an FFmpeg rational such as 30000/1001";
const MAX_FINDINGS: usize = 12;
pub(crate) struct HyperframesTool {
access: PathAccess,
}
impl HyperframesTool {
const NAME: &'static str = "hyperframes";
#[must_use]
pub(crate) const fn new(access: PathAccess) -> Self {
Self { access }
}
}
#[async_trait]
impl Tool for HyperframesTool {
fn name(&self) -> &'static str {
Self::NAME
}
fn is_advertised(&self) -> bool {
crate::tools::bun::bun_binary_path().is_some()
}
fn parameters_schema(&self) -> serde_json::Value {
let formats: Vec<&str> = Format::ALL.iter().map(|format| format.spelling()).collect();
let qualities: Vec<&str> = Quality::ALL
.iter()
.map(|quality| quality.spelling())
.collect();
let mut schema = super::tool_params_schema(
&json!({
"action": {
"type": "string",
"enum": ALL,
"description": "`instructions` for the field guide, `reference` for one deep topic, `inspect` to check a composition, `render` to write a video."
},
"topic": {
"type": "string",
"enum": TOPICS,
"description": "The reference document to return, for `reference`."
},
"composition": {
"type": "string",
"description": "For `render` and `inspect`: the composition — an `.html` file, or a project folder holding `index.html`."
},
"output": {
"type": "string",
"description": "For `render`: the file to write. Default: a new file in your workspace's `generated/`."
},
"format": {
"type": "string",
"enum": formats,
"description": "Default `mp4` (H.264). `webm` is VP9 with alpha, `mov` is ProRes 4444 with alpha, `gif` is a short silent loop."
},
"quality": {
"type": "string",
"enum": qualities,
"description": "Default `looks`: `draft` encodes fast, `delivery` is the cleanest."
},
"fps": {
"type": "string",
"description": format!("How many frames a second: {FPS_RULE}. Default: the composition's `data-fps`, else 30.")
},
"resolution": {
"type": "string",
"enum": RESOLUTIONS,
"description": "Captured at a higher device pixel ratio; the composition's aspect ratio must match."
}
}),
&["action"],
);
schema["additionalProperties"] = json!(false);
schema
}
fn media_marker(&self) -> Option<&'static str> {
Some("[VIDEO:")
}
fn preserve_full_output(&self) -> bool {
true
}
async fn execute(&self, ws: &Workspace, args: serde_json::Value) -> anyhow::Result<String> {
Ok(self
.answer(ws, args, super::TimelinePictures::TextOnly)
.await?
.text)
}
async fn execute_with_payloads(
&self,
ws: &Workspace,
args: serde_json::Value,
) -> anyhow::Result<super::ToolOutput> {
self.answer(ws, args, super::TimelinePictures::Attached)
.await
}
}
impl HyperframesTool {
async fn answer(
&self,
ws: &Workspace,
args: serde_json::Value,
pictures: super::TimelinePictures,
) -> anyhow::Result<super::ToolOutput> {
let text = match super::get_str(&args, "action")? {
"instructions" => crate::prompt::load_prompt("tool/hyperframes_instructions.md"),
"reference" => Self::reference(&args)?,
"inspect" => self.inspect(ws, &args).await?,
"render" => return self.render(ws, &args, pictures).await,
other => anyhow::bail!(
"usage: unknown action {other:?} — hint: use one of {}",
ALL.join(", ")
),
};
Ok(super::with_image_payload(self, text, ws, &args).await)
}
fn reference(args: &serde_json::Value) -> anyhow::Result<String> {
let topic = super::get_str(args, "topic")?;
if !TOPICS.contains(&topic) {
return Err(super::refuse_choice("topic", topic, &TOPICS));
}
Ok(crate::prompt::load_prompt(&format!(
"tool/hyperframes_{topic}.md"
)))
}
async fn inspect(&self, ws: &Workspace, args: &serde_json::Value) -> anyhow::Result<String> {
let requested = super::get_str(args, "composition")?;
let target = self.resolve_composition(ws, requested).await?;
let report = crate::hyperframes::lint(&target)
.await
.map_err(|reason| anyhow::anyhow!(reason))?;
Ok(format_report(&report))
}
async fn render(
&self,
ws: &Workspace,
args: &serde_json::Value,
pictures: super::TimelinePictures,
) -> anyhow::Result<super::ToolOutput> {
let requested = super::get_str(args, "composition")?;
let format = format_arg(args)?;
let quality = quality_arg(args)?;
let fps = super::get_opt_str_strict(args, "fps")?;
if let Some(fps) = fps
&& !valid_fps(fps)
{
anyhow::bail!("usage: `fps` must be {FPS_RULE} — got \"{fps}\"");
}
let resolution = super::get_opt_str_strict(args, "resolution")?;
if let Some(resolution) = resolution
&& !RESOLUTIONS.contains(&resolution)
{
return Err(super::refuse_choice("resolution", resolution, &RESOLUTIONS));
}
let target = self.resolve_composition(ws, requested).await?;
let reserved = self.output_path(ws, args, format).await?;
let (project, composition) = if target.is_dir() {
(target, None)
} else {
let root = match self.access {
PathAccess::Unrestricted => None,
_ => Some(ws.as_path()),
};
project_of(&target, root, |dir| dir.join("index.html").is_file())
};
let rendered = crate::hyperframes::render(RenderRequest {
project: &project,
composition: composition.as_deref(),
output: &reserved.path,
format,
quality,
fps,
resolution,
})
.await;
keep_state_out_of_git(&project);
let rendered = rendered.map_err(|reason| anyhow::anyhow!(reason))?;
Ok(self
.rendered_result(&reserved.keep(), format, fps, rendered, pictures)
.await)
}
async fn resolve_composition(
&self,
ws: &Workspace,
requested: &str,
) -> anyhow::Result<PathBuf> {
let target = super::path::resolve_read_target(ws.as_path(), requested, self.access).await?;
let meta = tokio::fs::metadata(&target)
.await
.map_err(|error| anyhow::anyhow!("cannot read {}: {error}", target.display()))?;
if meta.is_dir() {
anyhow::ensure!(
target.join("index.html").is_file(),
"cannot use {requested}: that folder has no index.html — hint: name the \
composition file, or a folder holding index.html"
);
return Ok(target);
}
anyhow::ensure!(
meta.is_file(),
"usage: {} is not a regular file or a directory — hint: name an `.html` composition, \
or a project folder holding index.html",
target.display()
);
Ok(target)
}
async fn output_path(
&self,
ws: &Workspace,
args: &serde_json::Value,
format: Format,
) -> anyhow::Result<Reservation> {
if let Some(requested) = super::get_opt_str_strict(args, "output")? {
let path =
super::path::resolve_write_target(ws.as_path(), requested, true, self.access)
.await?;
return Ok(Reservation::of(
claim(&with_format_extension(path, format)?).await?,
));
}
let dir = super::output_directory(ws, super::GENERATED_DIR);
tokio::fs::create_dir_all(&dir)
.await
.map_err(|error| anyhow::anyhow!("cannot create {}: {error}", dir.display()))?;
Ok(Reservation::of(
claim(&dir.join(format!(
"rendered_{}.{}",
crate::util::unix_millis(),
format.spelling()
)))
.await?,
))
}
async fn rendered_result(
&self,
output: &Path,
format: Format,
fps: Option<&str>,
rendered: Rendered,
pictures: super::TimelinePictures,
) -> super::ToolOutput {
let mut prefix = self.format_media_result(output);
if let Some(video) = rendered.info {
let (width, height) = video.size;
let mut sentence = format!(
"Rendered {:.1} s at {width}×{height}",
video.duration.as_secs_f64()
);
if let Some(fps) = fps.filter(|value| plain_integer(value)) {
let _ = write!(sentence, ", {fps} fps");
}
if let Ok(meta) = tokio::fs::metadata(output).await {
let _ = write!(
sentence,
", {}, {}.",
format.spelling().to_uppercase(),
super::listing::human_readable_size(meta.len())
);
let _ = write!(prefix, "\n\n{sentence}");
}
}
if let Some(note) = rendered.notes {
let _ = write!(prefix, "\n\n{note}");
}
super::video_output(prefix, output, pictures).await
}
}
fn keep_state_out_of_git(project: &Path) {
let state = project.join(".hyperframes");
if !state.is_dir() {
return;
}
let ignore = state.join(".gitignore");
let Ok(mut file) = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&ignore)
else {
return;
};
if std::io::Write::write_all(&mut file, b"*\n").is_err() {
drop(file);
let _ = std::fs::remove_file(&ignore);
}
}
fn project_of(
file: &Path,
root: Option<&Path>,
has_index: impl Fn(&Path) -> bool,
) -> (PathBuf, Option<String>) {
let own_dir = file.parent().unwrap_or(file);
let mut dir = own_dir;
let mut project = own_dir;
while root.is_none_or(|root| dir.starts_with(root)) {
if has_index(dir) {
project = dir;
break;
}
match dir.parent() {
Some(parent) => dir = parent,
None => break,
}
}
let relative = file
.strip_prefix(project)
.map(|path| {
path.components()
.map(|component| component.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/")
})
.unwrap_or_default();
let composition = (!relative.is_empty() && relative != "index.html").then_some(relative);
(project.to_path_buf(), composition)
}
fn with_format_extension(path: PathBuf, format: Format) -> anyhow::Result<PathBuf> {
let extension = format.spelling();
match path.extension().and_then(std::ffi::OsStr::to_str) {
Some(existing) if existing.eq_ignore_ascii_case(extension) => Ok(path),
Some(existing) if !existing.is_empty() => anyhow::bail!(
"format {extension} writes a .{extension} file, but the output is named .{existing} \
— hint: name a .{extension} file or change format"
),
_ => {
let mut named = path.into_os_string();
named.push(".");
named.push(extension);
Ok(PathBuf::from(named))
}
}
}
async fn claim(path: &Path) -> anyhow::Result<PathBuf> {
let (Some(name), Some(dir)) = (
path.file_name().and_then(std::ffi::OsStr::to_str),
path.parent(),
) else {
anyhow::bail!(
"cannot write {}: name a file with a UTF-8 name inside a folder",
path.display()
);
};
let (file, claimed) = crate::util::create_unique_file(dir, name)
.await
.map_err(|error| anyhow::anyhow!("cannot write {}: {error}", path.display()))?;
drop(file);
Ok(claimed)
}
struct Reservation {
path: PathBuf,
}
impl Reservation {
fn of(path: PathBuf) -> Self {
Self { path }
}
fn keep(mut self) -> PathBuf {
std::mem::take(&mut self.path)
}
}
impl Drop for Reservation {
fn drop(&mut self) {
if !self.path.as_os_str().is_empty() {
let _ = std::fs::remove_file(&self.path);
}
}
}
fn format_arg(args: &serde_json::Value) -> anyhow::Result<Format> {
match super::get_opt_str_strict(args, "format")? {
None => Ok(Format::Mp4),
Some(value) => Format::parse(value).ok_or_else(|| {
let allowed: Vec<&str> = Format::ALL.iter().map(|format| format.spelling()).collect();
super::refuse_choice("format", value, &allowed)
}),
}
}
fn quality_arg(args: &serde_json::Value) -> anyhow::Result<Quality> {
match super::get_opt_str_strict(args, "quality")? {
None => Ok(Quality::Looks),
Some(value) => Quality::parse(value).ok_or_else(|| {
let allowed: Vec<&str> = Quality::ALL
.iter()
.map(|quality| quality.spelling())
.collect();
super::refuse_choice("quality", value, &allowed)
}),
}
}
fn valid_fps(value: &str) -> bool {
if let Ok(fps) = value.parse::<u32>() {
return (1..=240).contains(&fps);
}
match value.split_once('/') {
Some((numerator, denominator)) => matches!(
(numerator.parse::<u32>(), denominator.parse::<u32>()),
(Ok(numerator), Ok(denominator)) if numerator > 0 && denominator > 0
),
None => false,
}
}
fn plain_integer(value: &str) -> bool {
!value.is_empty() && value.bytes().all(|byte| byte.is_ascii_digit())
}
fn format_report(report: &LintReport) -> String {
let mut out = counts_line(report);
let mut findings: Vec<&Finding> = report.findings.iter().collect();
findings.sort_by_key(|finding| severity_rank(&finding.severity));
for finding in findings.iter().take(MAX_FINDINGS) {
out.push('\n');
out.push_str(&finding_line(finding));
}
let hidden = findings.len().saturating_sub(MAX_FINDINGS);
if hidden > 0 {
let _ = write!(out, "\n…and {hidden} more");
}
out
}
fn counts_line(report: &LintReport) -> String {
let counts = [
(report.errors, "error"),
(report.warnings, "warning"),
(report.infos, "info"),
];
let stated: Vec<String> = counts
.into_iter()
.filter(|(count, _)| *count > 0)
.map(|(count, noun)| format!("{count} {noun}{}", if count == 1 { "" } else { "s" }))
.collect();
let files = format!(
"{} {}",
report.files,
if report.files == 1 { "file" } else { "files" }
);
if stated.is_empty() {
format!("no problems found in {files}")
} else {
format!("{} in {files}", stated.join(", "))
}
}
fn finding_line(finding: &Finding) -> String {
let severity = clean(&finding.severity);
let code = clean(&finding.code);
let mut line = if code.is_empty() {
format!("- {severity}")
} else {
format!("- {severity} {code}")
};
if let Some(location) = location(finding) {
let _ = write!(line, " ({location})");
}
let message = clean(&finding.message);
if !message.is_empty() {
let _ = write!(line, ": {message}");
}
if let Some(fix) = finding
.fix
.as_deref()
.map(clean)
.filter(|fix| !fix.is_empty())
{
let _ = write!(line, "\n fix: {fix}");
}
line
}
fn location(finding: &Finding) -> Option<String> {
let file = clean(finding.file.as_deref()?);
if file.is_empty() {
return None;
}
let name = Path::new(file).file_name().map_or_else(
|| file.to_string(),
|name| name.to_string_lossy().into_owned(),
);
Some(match finding.line {
Some(line) => format!("{name}:{line}"),
None => name,
})
}
fn severity_rank(severity: &str) -> u8 {
match clean(severity) {
"error" => 0,
"warning" => 1,
"info" => 2,
_ => 3,
}
}
fn clean(text: &str) -> &str {
text.trim_start_matches(|character: char| character.is_whitespace() || character == '\u{feff}')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_state_folder_is_kept_out_of_git_without_replacing_a_file() {
let dir = tempfile::tempdir().unwrap();
let project = dir.path();
let state = project.join(".hyperframes");
let ignore = state.join(".gitignore");
keep_state_out_of_git(project);
assert!(
!state.exists(),
"a project the renderer never ran in gets nothing from us"
);
std::fs::create_dir_all(&state).unwrap();
keep_state_out_of_git(project);
assert_eq!(std::fs::read_to_string(&ignore).unwrap(), "*\n");
std::fs::write(&ignore, "mine\n").unwrap();
keep_state_out_of_git(project);
assert_eq!(
std::fs::read_to_string(&ignore).unwrap(),
"mine\n",
"a file already there stands"
);
}
fn has_index_at(root: &Path) -> impl Fn(&Path) -> bool {
let root = root.to_path_buf();
move |dir| dir == root
}
#[test]
fn project_of_finds_the_nearest_index() {
let project = Path::new("project");
assert_eq!(
project_of(
Path::new("project/scene.html"),
Some(project),
has_index_at(project)
),
(project.to_path_buf(), Some("scene.html".to_string()))
);
assert_eq!(
project_of(
Path::new("project/compositions/intro.html"),
Some(project),
has_index_at(project)
),
(
project.to_path_buf(),
Some("compositions/intro.html".to_string())
)
);
assert_eq!(
project_of(
Path::new("project/index.html"),
Some(project),
has_index_at(project)
),
(project.to_path_buf(), None)
);
assert_eq!(
project_of(
Path::new("loose/clip.html"),
Some(Path::new("loose")),
|_| false
),
(PathBuf::from("loose"), Some("clip.html".to_string()))
);
assert_eq!(
project_of(
Path::new("ws/deep/clip.html"),
Some(Path::new("ws/deep")),
|dir| dir == Path::new("ws")
),
(PathBuf::from("ws/deep"), Some("clip.html".to_string()))
);
assert_eq!(
project_of(
Path::new("elsewhere/compositions/intro.html"),
None,
|dir| dir == Path::new("elsewhere")
),
(
PathBuf::from("elsewhere"),
Some("compositions/intro.html".to_string())
)
);
}
#[tokio::test]
async fn claim_never_hands_out_a_taken_name() {
let dir = tempfile::tempdir().unwrap();
let requested = dir.path().join("clip.mp4");
let first = claim(&requested).await.unwrap();
assert_eq!(first, requested);
assert!(first.is_file(), "the reservation is the claim itself");
let second = claim(&requested).await.unwrap();
assert_eq!(second, dir.path().join("clip_2.mp4"));
tokio::fs::write(&second, b"a finished render")
.await
.unwrap();
let third = claim(&requested).await.unwrap();
assert_eq!(third, dir.path().join("clip_3.mp4"));
assert_eq!(
tokio::fs::read(&second).await.unwrap(),
b"a finished render",
"an existing render is never touched"
);
}
#[tokio::test]
async fn a_named_output_in_a_new_folder_is_created_not_refused() {
let dir = tempfile::tempdir().unwrap();
let tool = HyperframesTool {
access: PathAccess::Workspace,
};
let ws = Workspace::from_path(dir.path());
let args = json!({ "output": "clips/2024/first.mp4" });
let claimed = tool
.output_path(&ws, &args, Format::Mp4)
.await
.expect("a new folder is created, not refused");
assert!(dir.path().join("clips/2024").is_dir());
assert!(
claimed.path.is_file(),
"the name is reserved before the render"
);
assert_eq!(claimed.path.file_name().unwrap(), "first.mp4");
let again = tool
.output_path(&ws, &args, Format::Mp4)
.await
.expect("the folder exists now");
assert_eq!(again.path.file_name().unwrap(), "first_2.mp4");
}
#[tokio::test]
async fn a_dropped_render_leaves_no_reserved_file_behind() {
let dir = tempfile::tempdir().unwrap();
let tool = HyperframesTool {
access: PathAccess::Workspace,
};
let ws = Workspace::from_path(dir.path());
let args = json!({ "output": "clip.mp4" });
let reserved = tool
.output_path(&ws, &args, Format::Mp4)
.await
.expect("the name is claimed");
let path = reserved.path.clone();
assert!(
path.is_file(),
"the reservation exists while the render runs"
);
drop(reserved);
assert!(
!path.exists(),
"a dropped render takes its reservation with it"
);
let retried = tool
.output_path(&ws, &args, Format::Mp4)
.await
.expect("the name is free again");
assert_eq!(retried.path.file_name().unwrap(), "clip.mp4");
let kept = retried.keep();
assert!(kept.is_file(), "a delivered render keeps its file");
}
}