mod browser;
mod install;
use std::ffi::OsString;
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::tools::shell::ProgramOutcome;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Format {
Mp4,
Webm,
Mov,
Gif,
}
impl Format {
pub(crate) const ALL: [Self; 4] = [Self::Mp4, Self::Webm, Self::Mov, Self::Gif];
pub(crate) fn parse(value: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|format| format.spelling() == value)
}
pub(crate) fn spelling(self) -> &'static str {
match self {
Self::Mp4 => "mp4",
Self::Webm => "webm",
Self::Mov => "mov",
Self::Gif => "gif",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Quality {
Draft,
Looks,
Delivery,
}
impl Quality {
pub(crate) const ALL: [Self; 3] = [Self::Draft, Self::Looks, Self::Delivery];
pub(crate) fn parse(value: &str) -> Option<Self> {
Self::ALL
.into_iter()
.find(|quality| quality.spelling() == value)
}
pub(crate) fn spelling(self) -> &'static str {
match self {
Self::Draft => "draft",
Self::Looks => "looks",
Self::Delivery => "delivery",
}
}
}
pub(crate) struct RenderRequest<'a> {
pub project: &'a Path,
pub composition: Option<&'a str>,
pub output: &'a Path,
pub format: Format,
pub quality: Quality,
pub fps: Option<&'a str>,
pub resolution: Option<&'a str>,
}
struct Runtime {
bun: PathBuf,
extra: Vec<(OsString, OsString)>,
shell: Option<browser::Shell>,
}
async fn runtime() -> Result<Runtime, String> {
let bun = crate::tools::bun::bun_binary_path()
.ok_or_else(|| "the product's managed bun runtime is not installed".to_string())?;
install::ensure_installed()
.await
.map_err(|reason| format!("the renderer could not be installed: {reason}"))?;
let extra = vec![
("HYPERFRAMES_NO_TELEMETRY".into(), "1".into()),
("DO_NOT_TRACK".into(), "1".into()),
("HYPERFRAMES_SKIP_SKILLS".into(), "1".into()),
];
Ok(Runtime {
bun,
extra,
shell: None,
})
}
async fn render_runtime() -> Result<Runtime, String> {
let mut runtime = runtime().await?;
let bin = crate::ffmpeg::binaries()
.await
.map_err(|reason| format!("the product's own FFmpeg payload is unavailable: {reason}"))?;
let shell = browser::ensure_shell()
.await
.map_err(|unavailable| match unavailable {
browser::Unavailable::Missing(reason) => {
format!("the renderer's browser is unavailable: {reason}")
}
browser::Unavailable::Unchecked(reason) => {
format!("the renderer's browser could not be checked: {reason}")
}
})?;
runtime.extra.push((
"HYPERFRAMES_FFMPEG_PATH".into(),
bin.ffmpeg.into_os_string(),
));
runtime.extra.push((
"HYPERFRAMES_FFPROBE_PATH".into(),
bin.ffprobe.into_os_string(),
));
runtime.extra.push((
"HYPERFRAMES_BROWSER_PATH".into(),
shell.binary.clone().into_os_string(),
));
runtime.shell = Some(shell);
Ok(runtime)
}
fn scratch(dir: &Path) -> Result<tempfile::TempDir, String> {
tempfile::Builder::new()
.prefix(".install-")
.tempdir_in(dir)
.map_err(|e| {
format!(
"the temporary directory for the download could not be created ({})",
e.kind()
)
})
}
const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(30);
const STALE_SCRATCH: Duration = DOWNLOAD_TIMEOUT.saturating_mul(2);
fn reclaim_scratch(dir: &Path) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let abandoned = name.starts_with(".install-")
&& entry
.metadata()
.and_then(|meta| meta.modified())
.ok()
.and_then(|modified| modified.elapsed().ok())
.is_some_and(|age| age > STALE_SCRATCH);
if abandoned {
crate::util::managed_bin::remove_any(&entry.path());
}
}
}
fn reclaim_aside(dir: &Path) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let aside = Path::new(&name)
.extension()
.is_some_and(|extension| extension.eq_ignore_ascii_case("old"));
if aside {
crate::util::managed_bin::remove_any(&entry.path());
}
}
}
async fn run(
bun: &Path,
args: &[String],
extra: &[(OsString, OsString)],
timeout: Option<Duration>,
) -> Result<ProgramOutcome, String> {
let cwd = install::dir()?;
let guarded: Vec<String> = crate::tools::bun::SCRIPT_GUARDS
.iter()
.map(|flag| (*flag).to_string())
.chain(args.iter().cloned())
.collect();
Ok(
crate::tools::shell::run_internal_program_outcome(&cwd, bun, &guarded, extra, timeout)
.await,
)
}
const RENDER: &str = "the render";
const CHECK: &str = "the check";
fn composition_argument(composition: &str) -> String {
if composition.starts_with('-') {
format!("./{composition}")
} else {
composition.to_string()
}
}
#[derive(Debug)]
pub(crate) struct Rendered {
pub(crate) info: Option<Video>,
pub(crate) notes: Option<String>,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Video {
pub(crate) duration: Duration,
pub(crate) size: (u32, u32),
}
enum Artifact {
Plays(Video),
Unplayable,
Unchecked(String),
}
pub(crate) async fn render(request: RenderRequest<'_>) -> Result<Rendered, String> {
let runtime = render_runtime().await?;
let (_held, entry) = install::hold_for_run().await?;
let mut args = vec![
entry.to_string_lossy().into_owned(),
"render".to_string(),
request.project.to_string_lossy().into_owned(),
];
if let Some(composition) = request.composition {
args.push("-c".to_string());
args.push(composition_argument(composition));
}
args.push("-o".to_string());
args.push(request.output.to_string_lossy().into_owned());
args.push("--format".to_string());
args.push(request.format.spelling().to_string());
args.push("--quality".to_string());
args.push(request.quality.spelling().to_string());
if let Some(fps) = request.fps {
args.push("--fps".to_string());
args.push(fps.to_string());
}
if let Some(resolution) = request.resolution {
args.push("--resolution".to_string());
args.push(resolution.to_string());
}
args.push("--experimental-fast-capture=false".to_string());
args.push("--json".to_string());
let outcome = run(&runtime.bun, &args, &runtime.extra, None).await?;
let artifact = artifact(request.output).await;
render_verdict(artifact, &outcome, request.output)
}
fn delivery_notes(outcome: &ProgramOutcome) -> Option<String> {
let late = late_failure(&outcome.output);
let mut named = None;
let mut notes = Vec::new();
if outcome.stopped() {
notes.push(format!(
"the product stopped the render after the file was written: {}",
outcome.stop_reason()
));
} else if let Some(failure) = failure_envelope(&outcome.output) {
let entry = after_write_failure(&failure);
let fuller = late.as_ref().filter(|late| {
same_failure(&entry.message, &late.message)
&& words(&late.message).len() > words(&entry.message).len()
});
let entry_tells = !entry.message.is_empty() || late.is_none();
if let Some(late) = fuller {
named = Some(late.message.clone());
notes.push(late.sentence.clone());
} else if entry_tells {
named = Some(entry.message);
notes.push(entry.sentence);
}
} else if !outcome.success {
notes.push(format!(
"the file was written; the renderer's run ended: {}",
outcome.detail
));
}
if let Some(late) = late
&& !named.is_some_and(|named| same_failure(&named, &late.message))
{
notes.push(late.sentence);
}
(!notes.is_empty()).then(|| notes.join("\n"))
}
fn same_failure(one: &str, other: &str) -> bool {
let (one, other) = (words(one), words(other));
let (shorter, longer) = if one.len() <= other.len() {
(one, other)
} else {
(other, one)
};
!shorter.is_empty()
&& (longer.starts_with(shorter.as_slice()) || longer.ends_with(shorter.as_slice()))
}
fn after_write_failure(failure: &Envelope) -> PostWrite {
let message = one_line(&without_remedies(&failure.message));
let named = failure.headline(&message);
let named = if named.trim().is_empty() {
"no diagnosis".to_string()
} else {
crate::util::cut_bytes(&named, NOTE_BUDGET_BYTES)
};
PostWrite {
sentence: format!(
"the file was written; the renderer reported a failure after the write: {named}"
),
message,
}
}
fn one_line(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn words(text: &str) -> Vec<String> {
text.split(|character: char| !character.is_alphanumeric())
.filter(|word| !word.is_empty())
.map(str::to_ascii_lowercase)
.collect()
}
fn render_verdict(
artifact: Artifact,
outcome: &ProgramOutcome,
output: &Path,
) -> Result<Rendered, String> {
match artifact {
Artifact::Plays(video) => Ok(Rendered {
info: Some(video),
notes: delivery_notes(outcome),
}),
Artifact::Unchecked(reason) => {
let unchecked = format!("this machine could not check the file: {reason}");
let notes = delivery_notes(outcome);
Ok(Rendered {
info: None,
notes: Some(match notes {
Some(note) => format!("{note}\n{unchecked}"),
None => unchecked,
}),
})
}
Artifact::Unplayable => Err(render_failure(outcome, output)),
}
}
async fn artifact(output: &Path) -> Artifact {
let non_empty = tokio::fs::metadata(output)
.await
.is_ok_and(|meta| meta.len() > 0);
if !non_empty {
return Artifact::Unplayable;
}
match crate::ffmpeg::probe(output).await {
Err(crate::ffmpeg::FfmpegError::Unavailable(reason)) => Artifact::Unchecked(reason),
Err(crate::ffmpeg::FfmpegError::TimedOut) => {
Artifact::Unchecked("the probe did not finish in time".to_string())
}
Ok(info) => match info.dimensions {
Some(size) => Artifact::Plays(Video {
duration: info.duration,
size,
}),
None => Artifact::Unplayable,
},
Err(_) => Artifact::Unplayable,
}
}
fn render_failure(outcome: &ProgramOutcome, output: &Path) -> String {
if !outcome.success {
return run_failure(outcome, RENDER, None);
}
if let Some(failure) = failure_envelope(&outcome.output) {
return envelope_failure(&failure, RENDER);
}
let mut message = format!(
"{RENDER} failed: the renderer exited clean but wrote no playable file at {}",
output.display()
);
let tail = without_remedies(&failure_tail(&outcome.output));
if !tail.is_empty() {
let _ = write!(message, "\n{tail}");
}
crate::util::cut_bytes(&message, MESSAGE_BUDGET_BYTES)
}
pub(crate) struct LintReport {
pub(crate) errors: usize,
pub(crate) warnings: usize,
pub(crate) infos: usize,
pub(crate) files: usize,
pub(crate) findings: Vec<Finding>,
}
pub(crate) struct Finding {
pub(crate) severity: String,
pub(crate) code: String,
pub(crate) message: String,
pub(crate) fix: Option<String>,
pub(crate) file: Option<String>,
pub(crate) line: Option<u64>,
}
pub(crate) async fn lint(target: &Path) -> Result<LintReport, String> {
let runtime = runtime().await?;
let (_held, entry) = install::hold_for_run().await?;
let args = vec![
entry.to_string_lossy().into_owned(),
"lint".to_string(),
target.to_string_lossy().into_owned(),
"--json".to_string(),
];
let ceiling = crate::tools::shell::DEFAULT_SHELL_TIMEOUT;
let outcome = run(&runtime.bun, &args, &runtime.extra, Some(ceiling)).await?;
if let Some(report) = lint_report(&outcome.output) {
return Ok(report);
}
if outcome.stopped() {
return Err(run_failure(&outcome, CHECK, Some(ceiling)));
}
if let Some(failure) = failure_envelope(&outcome.output) {
return Err(envelope_failure(&failure, CHECK));
}
if outcome.success {
return Err(format!(
"{CHECK} exited clean but printed no report this tool could read"
));
}
Err(run_failure(&outcome, CHECK, Some(ceiling)))
}
fn json_answer(output: &str) -> Option<serde_json::Value> {
let mut at = 0;
for line in output.split_inclusive('\n') {
let trimmed = line.trim_start();
if trimmed.starts_with('{') {
let start = at + (line.len() - trimmed.len());
let answer = serde_json::Deserializer::from_str(&output[start..])
.into_iter::<serde_json::Value>()
.next();
if let Some(Ok(value)) = answer
&& value.is_object()
{
return Some(value);
}
}
at += line.len();
}
None
}
fn lint_report(output: &str) -> Option<LintReport> {
let answer = json_answer(output)?;
let failed = answer.get("ok").and_then(serde_json::Value::as_bool) == Some(false)
&& answer
.get("filesScanned")
.and_then(serde_json::Value::as_u64)
== Some(0);
if answer.get("error").is_some() || failed {
return None;
}
let is_report = [
"errorCount",
"warningCount",
"infoCount",
"filesScanned",
"findings",
]
.iter()
.any(|key| answer.get(key).is_some());
if !is_report {
return None;
}
let count = |key: &str| {
usize::try_from(
answer
.get(key)
.and_then(serde_json::Value::as_u64)
.unwrap_or(0),
)
.unwrap_or_default()
};
let findings = answer
.get("findings")
.and_then(serde_json::Value::as_array)
.map(|findings| {
findings
.iter()
.map(|finding| Finding {
severity: text(finding, "severity").unwrap_or_default(),
code: text(finding, "code").unwrap_or_default(),
message: text(finding, "message")
.map(|message| without_remedies(&message))
.unwrap_or_default(),
fix: text(finding, "fixHint")
.map(|fix| without_remedies(&fix))
.filter(|fix| !fix.is_empty()),
file: text(finding, "file"),
line: finding.get("line").and_then(serde_json::Value::as_u64),
})
.collect()
})
.unwrap_or_default();
Some(LintReport {
errors: count("errorCount"),
warnings: count("warningCount"),
infos: count("infoCount"),
files: count("filesScanned"),
findings,
})
}
fn text(value: &serde_json::Value, key: &str) -> Option<String> {
value
.get(key)
.and_then(serde_json::Value::as_str)
.map(str::to_string)
}
fn machine_side_gap(message: &str) -> Option<&'static str> {
let lower = message.to_ascii_lowercase();
if lower.contains("encoder unavailable") {
return Some(
"the product's own FFmpeg payload has no encoder for this format on this machine, \
which is a machine-side gap rather than a composition problem",
);
}
if lower.contains("chrome") && (lower.contains("launch") || lower.contains("not found")) {
return Some(
"the product's own browser build could not start, which is a machine-side gap \
rather than a composition problem",
);
}
None
}
struct Envelope {
code: Option<String>,
message: String,
hint: Option<String>,
}
impl Envelope {
fn headline(&self, message: &str) -> String {
match self.code.as_deref().filter(|code| !code.is_empty()) {
Some(code) if message.is_empty() => code.to_string(),
Some(code) => format!("{code}: {message}"),
None => message.to_string(),
}
}
}
fn failure_envelope(output: &str) -> Option<Envelope> {
let answer = json_answer(output)?;
if answer.get("ok").and_then(serde_json::Value::as_bool) != Some(false) {
return None;
}
let error = answer.get("error")?;
Some(Envelope {
code: text(error, "code"),
message: text(error, "message")?,
hint: text(error, "hint"),
})
}
fn run_failure(outcome: &ProgramOutcome, subject: &str, ceiling: Option<Duration>) -> String {
if let (true, Some(ceiling)) = (outcome.timed_out(), ceiling) {
return crate::tools::shell::timeout_sentence(subject, ceiling);
}
let envelope = (!outcome.stopped())
.then(|| failure_envelope(&outcome.output))
.flatten();
let Some(failure) = envelope else {
let tail = without_remedies(&failure_tail(&outcome.output));
let text = if tail.is_empty() {
format!("{subject} failed: {}", outcome.detail)
} else {
format!("{subject} failed: {}\n{tail}", outcome.detail)
};
return crate::util::cut_bytes(&text, MESSAGE_BUDGET_BYTES);
};
envelope_failure(&failure, subject)
}
fn envelope_failure(failure: &Envelope, subject: &str) -> String {
let message = without_remedies(&failure.message);
let head = failure.headline(&message);
let diagnosis = format!(
"{} {}",
failure.message,
failure.hint.as_deref().unwrap_or_default()
);
let note = machine_side_gap(&diagnosis)
.map(|note| format!(" — {note}"))
.unwrap_or_default();
let hint = failure
.hint
.as_deref()
.filter(|hint| !hint.trim().is_empty())
.map(without_remedies)
.filter(|hint| !hint.is_empty())
.map(|hint| {
let hint = crate::util::cut_bytes(&hint, HINT_BUDGET_BYTES);
format!("\n hint: {hint}")
})
.unwrap_or_default();
let head = crate::util::cut_bytes(
&head,
MESSAGE_BUDGET_BYTES.saturating_sub(note.len() + hint.len()),
);
let message = format!("{head}{note}{hint}");
if message.trim().is_empty() {
return format!("{subject} reported a failure without a diagnosis");
}
message
}
fn failure_tail(output: &str) -> String {
const LINES: usize = 8;
let lines: Vec<&str> = output
.lines()
.map(str::trim)
.filter(|line| !line.is_empty() && !line.starts_with('[') && !line.starts_with("(node:"))
.filter(|line| !line.starts_with('{'))
.filter(|line| !line.starts_with(SPURIOUS))
.collect();
lines[lines.len().saturating_sub(LINES)..].join("\n")
}
const SPURIOUS: &str = "No composition found in ";
struct PostWrite {
message: String,
sentence: String,
}
fn late_failure(output: &str) -> Option<PostWrite> {
const MARKERS: [&str; 2] = [
"failed (render already succeeded): ",
"delivered its result): ",
];
let line = output
.lines()
.rev()
.find(|line| MARKERS.iter().any(|marker| line.contains(marker)))?;
let rest = MARKERS.iter().find_map(|marker| line.split_once(marker))?.1;
let message = one_line(&without_remedies(rest));
if message.is_empty() {
return None;
}
Some(PostWrite {
sentence: format!(
"the file was written; a step after the render failed: {}",
crate::util::cut_bytes(&message, NOTE_BUDGET_BYTES)
),
message,
})
}
const CLAUSE_ENDS: [&str; 7] = [". ", "; ", ", ", " — ", " - ", ": ", " ("];
const SEPARATORS: [char; 6] = [' ', ';', ',', ':', '—', '-'];
const CONDITIONALS: [&str; 3] = ["if ", "when ", "unless "];
const VENDOR_COMMANDS: [&str; 49] = [
"add",
"audio",
"auth",
"beats",
"benchmark",
"browser",
"capture",
"catalog",
"catch-up",
"check",
"clean",
"cloud",
"cloudrun",
"compare",
"compositions",
"docs",
"doctor",
"events",
"feedback",
"figma",
"grade-compare",
"history",
"info",
"init",
"inspect",
"keyframes",
"lambda",
"layout",
"lint",
"media-treatment",
"media-use",
"models",
"normalize-audio",
"open",
"play",
"present",
"preview",
"publish",
"remove-background",
"render",
"skills",
"snapshot",
"telemetry",
"timeline",
"transcribe",
"tts",
"upgrade",
"usage",
"validate",
];
const KNOB_LINES: [&str; 2] = ["env:", "cli:"];
const INSTRUCTIONS: [&str; 6] = [
"install ",
"please ",
"reinstall ",
"run ",
"try ",
"scaffold ",
];
const REMEDIES: [&str; 9] = [
"apt install",
"apt-get install",
"brew install",
"bun add",
"bunx ",
"npm i",
"npx ",
"yarn add",
"--docker",
];
fn without_remedies(text: &str) -> String {
text.lines()
.filter(|line| !line.trim().is_empty())
.filter_map(without_advice)
.collect::<Vec<_>>()
.join("\n")
}
fn without_advice(line: &str) -> Option<String> {
let beginning = line.trim_start().to_ascii_lowercase();
if KNOB_LINES.iter().any(|knob| beginning.starts_with(knob)) {
return None;
}
let mut kept = String::new();
let mut gap = false;
let mut dropped = false;
let mut start = 0;
let mut from = 0;
while let Some((at, end)) = next_clause_end(line, from) {
if end == " (" {
match parenthetical_end(line, at) {
Some(close) if is_advice(&line[at + end.len()..close]) => {
dropped = true;
if !is_advice(&line[start..at]) {
join_kept(&mut kept, &mut gap, &line[start..at]);
}
gap = true;
start = close + 1;
from = start;
}
kept_parenthetical => {
from = kept_parenthetical.map_or(at + end.len(), |close| close + 1);
}
}
continue;
}
from = at + end.len();
if (end == ", " && is_conditional(&line[start..at]))
|| (end == ": " && is_cue(&line[start..at]))
{
continue;
}
if is_advice(&line[start..at]) {
dropped = true;
gap = true;
} else {
join_kept(&mut kept, &mut gap, &line[start..at + end.len()]);
}
start = at + end.len();
}
if is_advice(&line[start..]) {
dropped = true;
gap = true;
} else {
join_kept(&mut kept, &mut gap, &line[start..]);
}
if !dropped {
return Some(line.to_string());
}
let kept = if gap {
kept.trim_end_matches(SEPARATORS)
} else {
kept.trim()
};
if kept.is_empty() {
return (!opens_as_instruction(&opening(line))).then(|| line.to_string());
}
if is_fragment(kept) || !balanced(kept) {
return Some(line.to_string());
}
Some(kept.to_string())
}
fn join_kept(kept: &mut String, gap: &mut bool, text: &str) {
let text = if *gap {
text.trim_start_matches(SEPARATORS)
} else {
text
};
if text.is_empty() {
return;
}
let word_ends = |kept: &str| {
kept.ends_with(|c: char| c.is_alphanumeric() || matches!(c, ')' | '"' | '\'' | '`'))
};
let word_begins = |text: &str| {
text.starts_with(|c: char| c.is_alphanumeric() || matches!(c, '(' | '"' | '\'' | '`'))
};
if *gap && word_ends(kept) && word_begins(text) {
kept.push(' ');
}
kept.push_str(text);
*gap = false;
}
fn balanced(text: &str) -> bool {
let mut depth = 0_u32;
for character in text.chars() {
match character {
'(' => depth += 1,
')' => match depth.checked_sub(1) {
Some(shallower) => depth = shallower,
None => return false,
},
_ => {}
}
}
depth == 0
}
fn is_fragment(left: &str) -> bool {
const CONNECTORS: [&str; 13] = [
"and", "or", "but", "then", "with", "to", "for", "the", "run", "try", "use", "install",
"via",
];
left.split_whitespace()
.next_back()
.map(|word| word.to_ascii_lowercase().trim_end_matches(',').to_string())
.is_some_and(|word| CONNECTORS.contains(&word.as_str()))
}
fn is_cue(clause: &str) -> bool {
const CUES: [&str; 5] = ["run", "try", "use", "install", "hint"];
let clause = clause.trim().to_ascii_lowercase();
CUES.contains(&clause.as_str())
}
fn is_conditional(clause: &str) -> bool {
let clause = clause.trim_start().to_ascii_lowercase();
CONDITIONALS.iter().any(|opener| clause.starts_with(opener))
}
fn next_clause_end(line: &str, from: usize) -> Option<(usize, &'static str)> {
CLAUSE_ENDS
.iter()
.filter_map(|end| line[from..].find(end).map(|at| (from + at, *end)))
.min_by_key(|(at, _)| *at)
}
fn parenthetical_end(line: &str, at: usize) -> Option<usize> {
let opened = at + " (".len();
line[opened..].find(')').map(|close| opened + close)
}
fn is_advice(clause: &str) -> bool {
let clause = opening(clause);
opens_as_instruction(&clause) || carries_remedy(&clause)
}
fn opens_as_instruction(clause: &str) -> bool {
INSTRUCTIONS.iter().any(|opener| clause.starts_with(opener))
|| REMEDIES.iter().any(|runner| clause.starts_with(runner))
|| opens_with_command(clause)
}
fn carries_remedy(clause: &str) -> bool {
REMEDIES.iter().any(|remedy| {
clause.match_indices(remedy).any(|(at, _)| {
remedy.ends_with(' ')
|| clause[at + remedy.len()..]
.chars()
.next()
.is_none_or(|next| !next.is_ascii_alphanumeric())
})
})
}
fn opening(clause: &str) -> String {
let clause = clause
.trim()
.trim_start_matches(['(', '`', ' '])
.to_ascii_lowercase();
let mut clause = strip_connectors(clause);
if let Some((cue, instruction)) = clause.split_once(": ")
&& is_cue(cue)
{
clause = strip_connectors(instruction.to_string());
}
if CONDITIONALS.iter().any(|opener| clause.starts_with(opener))
&& let Some((_, consequence)) = clause.split_once(", ")
{
clause = strip_connectors(consequence.to_string());
}
clause
}
fn strip_connectors(mut clause: String) -> String {
'outer: loop {
for connector in ["or ", "and ", "then ", "so "] {
if let Some(rest) = clause.strip_prefix(connector) {
clause = rest.to_string();
continue 'outer;
}
}
return clause;
}
}
fn opens_with_command(clause: &str) -> bool {
let Some(rest) = clause.strip_prefix("hyperframes ") else {
return false;
};
let word: String = rest
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '-')
.collect();
VENDOR_COMMANDS.contains(&word.as_str())
}
const MESSAGE_BUDGET_BYTES: usize = 1200;
const HINT_BUDGET_BYTES: usize = 800;
const NOTE_BUDGET_BYTES: usize = 400;
pub async fn refresh_on_start() {
install::refresh_on_start().await;
}
#[cfg(test)]
mod tests {
use crate::tools::shell::Stop;
use super::*;
fn failed(output: &str) -> ProgramOutcome {
ProgramOutcome {
success: false,
detail: "exit status 1".to_string(),
output: output.to_string(),
has_output: true,
stop: None,
}
}
#[cfg(unix)]
#[test]
fn a_sweep_takes_the_abandoned_scratch_and_the_aside_and_leaves_the_live_one() {
let dir = tempfile::tempdir().unwrap();
for name in [".install-live", ".install-dead", "node_modules.old"] {
std::fs::create_dir_all(dir.path().join(name)).unwrap();
}
let dead = std::fs::File::open(dir.path().join(".install-dead")).unwrap();
dead.set_times(
std::fs::FileTimes::new().set_modified(
std::time::SystemTime::now() - STALE_SCRATCH - Duration::from_mins(1),
),
)
.unwrap();
reclaim_scratch(dir.path());
reclaim_aside(dir.path());
assert!(
dir.path().join(".install-live").exists(),
"a download in flight is not ours to remove"
);
assert!(
!dir.path().join(".install-dead").exists(),
"an abandoned scratch tree goes"
);
assert!(
!dir.path().join("node_modules.old").exists(),
"a tree a swap set aside goes with it, whatever it was called"
);
}
#[test]
fn lint_report_reads_the_pretty_printed_answer() {
let output = "{\n \"ok\": false,\n \"errorCount\": 2,\n \"warningCount\": 1,\n \
\"infoCount\": 0,\n \"findings\": [\n {\n \"code\": \"root_missing_dimensions\",\n \
\"severity\": \"error\",\n \"message\": \"Root composition is missing data-width.\",\n \
\"fixHint\": \"Set numeric data-width.\",\n \"file\": \"/w/index.html\",\n \
\"line\": 1\n },\n {\n \"code\": \"viewport_mismatch\",\n \
\"severity\": \"error\",\n \"message\": \"The viewport does not match.\",\n \
\"fixHint\": \"update the meta viewport to match, or scaffold with `hyperframes init \
--resolution portrait`\"\n }\n ],\n \"filesScanned\": 1\n}\n[initSession] noise\n";
let report = lint_report(output).expect("the report is read");
assert_eq!(
(report.errors, report.warnings, report.infos, report.files),
(2, 1, 0, 1)
);
assert_eq!(report.findings.len(), 2);
assert_eq!(report.findings[0].code, "root_missing_dimensions");
assert_eq!(report.findings[0].line, Some(1));
assert_eq!(
report.findings[0].fix.as_deref(),
Some("Set numeric data-width.")
);
assert_eq!(
report.findings[1].fix.as_deref(),
Some("update the meta viewport to match"),
"the fix stays, the vendor's own command does not"
);
}
#[test]
fn a_failure_envelope_is_not_read_as_a_clean_report() {
let output = "{\n \"ok\": false,\n \"error\": {\"code\": \"runtime_error\", \
\"message\": \"No composition found in /w\"},\n \"findings\": [],\n \
\"errorCount\": 0,\n \"warningCount\": 0,\n \"infoCount\": 0,\n \
\"filesScanned\": 0\n}\n";
assert!(lint_report(output).is_none(), "got: {output}");
let message = run_failure(&failed(output), "the check", None);
assert!(
message.starts_with("runtime_error: No composition found in /w"),
"got: {message}"
);
}
#[test]
fn the_file_decides_the_render_not_the_run() {
let unplayable = Path::new("/work/clip.mp4");
let run = failed("");
let plays = || {
Artifact::Plays(Video {
duration: Duration::from_secs(6),
size: (1920, 1080),
})
};
let delivered =
render_verdict(plays(), &run, unplayable).expect("a playable file is a result");
assert!(
delivered
.notes
.is_some_and(|note| note.contains("exit status 1")),
"a bad run is noted beside the file it did produce"
);
assert_eq!(
delivered.info.expect("the facts are kept").size,
(1920, 1080)
);
let complained = failed(
" [hyperframes] Post-render step 'history' failed (render already succeeded): \
history.json could not be written\n",
);
let delivered = render_verdict(plays(), &complained, unplayable).expect("the file stands");
assert!(
delivered.notes.unwrap().contains("history.json"),
"the note names what failed after the write"
);
let delivered = render_verdict(
Artifact::Unchecked("the probe did not finish in time".to_string()),
&complained,
unplayable,
)
.expect("a file the machine cannot judge is kept");
assert!(delivered.info.is_none());
let note = delivered.notes.expect("the note names what happened");
assert!(note.contains("history.json"), "got: {note}");
assert!(
note.contains("could not check the file"),
"the note says the file went unchecked: {note}"
);
assert_eq!(
render_verdict(Artifact::Unplayable, &run, unplayable).unwrap_err(),
"the render failed: exit status 1"
);
}
#[test]
fn a_delivered_file_carries_how_the_run_ended_badly() {
let plays = || {
Artifact::Plays(Video {
duration: Duration::from_secs(6),
size: (1280, 720),
})
};
let killed = ProgramOutcome {
detail: "terminated: exceeded memory limit (used ~15.4 GiB of 18.0 GiB)".to_string(),
stop: Some(Stop::Memory),
..failed("")
};
let note = delivery_notes(&killed).expect("the stop is named");
assert_eq!(
note,
"the product stopped the render after the file was written: \
exceeded memory limit (used ~15.4 GiB of 18.0 GiB)",
"the stop is named once"
);
let crashed = failed("Rendering frame 179 of 180\n");
let note = delivery_notes(&crashed).expect("the exit status is named");
assert_eq!(
note,
"the file was written; the renderer's run ended: exit status 1"
);
let reported = failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"history.json \
could not be written\",\"hint\":\"run hyperframes doctor\"}}\n",
);
let note = delivery_notes(&reported).expect("the renderer's failure is named");
assert_eq!(
note,
"the file was written; the renderer reported a failure after the write: \
runtime_error: history.json could not be written"
);
let twice = failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"history.json \
could not be written\"}}\n [hyperframes] Post-render step 'history' failed \
(render already succeeded): history.json could not be written\n",
);
let note = delivery_notes(&twice).expect("one sentence names it");
assert_eq!(note.matches("history.json").count(), 1, "got: {note}");
assert!(
note.starts_with("the file was written; the renderer reported a failure"),
"the entry leads: {note}"
);
let fuller = failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"history.json \
could not be written\"}}\n [hyperframes] Post-render step 'history' failed \
(render already succeeded): history.json could not be written: permission denied \
on the state folder\n",
);
let note = delivery_notes(&fuller).expect("one sentence names it");
assert_eq!(note.matches("history.json").count(), 1, "got: {note}");
assert!(
note.contains("permission denied"),
"the fuller telling is kept: {note}"
);
let wrapped = failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"Post-render step \
'history' failed (render already succeeded): history.json could not be written\"}}\n \
[hyperframes] Late step failed (render already succeeded): history.json could not be \
written\n",
);
let note = delivery_notes(&wrapped).expect("one sentence names it");
assert_eq!(note.matches("history.json").count(), 1, "got: {note}");
let code_only = failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"run hyperframes \
doctor\"}}\n [hyperframes] Post-render step 'history' failed (render already \
succeeded): history.json could not be written\n",
);
let note = delivery_notes(&code_only).expect("the complaint names it");
assert_eq!(note.matches("history.json").count(), 1, "got: {note}");
assert!(
!note.contains("runtime_error"),
"one sentence, not two: {note}"
);
let code_alone = failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"run hyperframes \
doctor\"}}\n",
);
assert!(delivery_notes(&code_alone).is_some_and(|note| note.ends_with("runtime_error")));
let delivered = render_verdict(plays(), &crashed, Path::new("/work/clip.mp4"))
.expect("the file stands");
assert!(delivered.notes.unwrap().contains("exit status 1"));
let stopped = ProgramOutcome {
detail: "terminated: exceeded memory limit (used ~15.4 GiB of 18.0 GiB)".to_string(),
stop: Some(Stop::Memory),
..failed(
" [hyperframes] Post-render step 'history' failed (render already succeeded): \
history.json could not be written\n",
)
};
let note = delivery_notes(&stopped).expect("both facts are kept");
let stop = note
.find("the product stopped the render")
.expect("the stop");
let complaint = note.find("history.json").expect("the complaint");
assert!(stop < complaint, "the stop leads: {note}");
}
#[test]
fn a_run_the_product_ended_reports_its_own_stop_reason() {
let outcome = ProgramOutcome {
detail: "terminated: exceeded memory limit (used ~15.4 GiB of 18.0 GiB)".to_string(),
stop: Some(Stop::Memory),
..failed("capturing frame 18 of 30\n")
};
assert_eq!(
run_failure(&outcome, RENDER, None),
"the render failed: terminated: exceeded memory limit (used ~15.4 GiB of 18.0 GiB)\n\
capturing frame 18 of 30"
);
let outcome = ProgramOutcome {
detail: "terminated: exceeded memory limit (used ~15.4 GiB of 18.0 GiB)".to_string(),
stop: Some(Stop::Memory),
..failed(
"{\"ok\":false,\"error\":{\"code\":\"runtime_error\",\"message\":\"page threw\"}}\n",
)
};
let message = run_failure(&outcome, RENDER, None);
assert!(
message.starts_with("the render failed: terminated: exceeded memory limit"),
"got: {message}"
);
assert!(!message.contains("page threw"), "got: {message}");
}
const ADVICE_CASES: [(&str, &str); 37] = [
(
"Try --docker for containerized rendering. The script threw at line 42.",
"The script threw at line 42.",
),
(
"The script threw at line 42. Try --docker for containerized rendering.",
"The script threw at line 42.",
),
(
"Install a working 64-bit FFmpeg build with all required runtime DLLs.",
"",
),
("Please install a working FFmpeg build", ""),
(
"the install step of the page threw a TypeError",
"the install step of the page threw a TypeError",
),
(
"the composition did not run: TypeError",
"the composition did not run: TypeError",
),
("Run: npx hyperframes browser ensure", ""),
(
"The script threw at line 42 and then run hyperframes doctor",
"The script threw at line 42 and then run hyperframes doctor",
),
("The page threw a TypeError;", "The page threw a TypeError;"),
(
"The clip ended early (data-duration 2).",
"The clip ended early (data-duration 2).",
),
("Failed (run hyperframes doctor, then retry)", "Failed"),
(
"The page threw (run hyperframes doctor) (exit 1)",
"The page threw (exit 1)",
),
(
"The page threw. run hyperframes doctor (exit 1)",
"The page threw.",
),
(
"The page threw (run hyperframes doctor, then check the asset).",
"The page threw.",
),
("run hyperframes doctor (see docs) then render again", ""),
(
"Render failed (exit 1) then run npx hyperframes doctor",
"Render failed (exit 1) then run npx hyperframes doctor",
),
(
"The npm install step failed: EACCES on /usr/lib/node_modules",
"The npm install step failed: EACCES on /usr/lib/node_modules",
),
(
"Run npm i. The page threw a TypeError;",
"The page threw a TypeError;",
),
(
"Render failed - see docs - run npx hyperframes doctor",
"Render failed - see docs",
),
(
"Env: PRODUCER_PAGE_NAVIGATION_TIMEOUT_MS\nThe page did not load.",
"The page did not load.",
),
(
"The script threw at line 42; try --docker",
"The script threw at line 42",
),
(
"The script threw at line 42 — run hyperframes doctor to check the media",
"The script threw at line 42",
),
(
"The script threw at line 42: run hyperframes doctor",
"The script threw at line 42",
),
(
"The script threw at line 42 (run hyperframes doctor)",
"The script threw at line 42",
),
("Render failed (exit code 1)", "Render failed (exit code 1)"),
(
"Render failed (exit 1; run hyperframes doctor)",
"Render failed (exit 1; run hyperframes doctor)",
),
(
"The composition is blank. hyperframes snapshot shows why",
"The composition is blank.",
),
(
"If clip.mp4 fails to play in preview, run hyperframes doctor and confirm \
media.autoProxy is not false.",
"",
),
(
"update the meta viewport to match, or scaffold with `hyperframes init \
--resolution portrait`",
"update the meta viewport to match",
),
("bunx hyperframes render .", ""),
(
"The hyperframes package is not compatible with this Node version",
"The hyperframes package is not compatible with this Node version",
),
(
"Compatibility with hyperframes 0.9 requires a newer runtime",
"Compatibility with hyperframes 0.9 requires a newer runtime",
),
(
" The page threw a TypeError ",
" The page threw a TypeError ",
),
(
"Install an FFmpeg build with libx264 support (brew install ffmpeg), or render \
WebM instead: hyperframes render .",
"or render WebM instead",
),
(
"(brew install ffmpeg), or the page threw a TypeError",
"or the page threw a TypeError",
),
(
"The encoder is missing. Install an FFmpeg build (brew install ffmpeg), or render \
WebM instead: hyperframes render .",
"The encoder is missing. or render WebM instead",
),
(
"Failed to read the capture path; Alternatively, install FFmpeg with libx264",
"Failed to read the capture path; Alternatively",
),
];
#[test]
fn advice_never_takes_the_diagnosis_with_it() {
for (line, kept) in ADVICE_CASES {
assert_eq!(without_remedies(line), kept, "for: {line}");
}
}
#[test]
fn the_filter_never_damages_what_it_keeps() {
const WORDS: [&str; 28] = [
"run",
"hyperframes",
"doctor",
"npx",
"install",
"the",
"page",
"threw",
"exit",
"Failed",
"render",
"Try",
"see",
"docs",
"retry",
"asset",
"check",
"and",
"if",
"clip.mp4",
"preview,",
"then",
"again.",
";",
":",
"(",
")",
"exit)",
];
let mut state = 0x2545_f491_4f6c_dd1d_u64;
let mut next = move || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for _ in 0..500 {
let mut line = String::new();
for _ in 0..=next() % 10 {
let word = WORDS[usize::try_from(next() % WORDS.len() as u64).unwrap_or_default()];
line.push_str(if line.is_empty() { "" } else { " " });
line.push_str(word);
}
let starting_balanced = balanced(&line);
for kept in without_remedies(&line).lines() {
assert!(
!starting_balanced || balanced(kept) || kept == line,
"unbalanced from {line:?}: {kept:?}"
);
for word in kept
.split(|c: char| !c.is_alphanumeric())
.filter(|word| word.len() > 1)
{
assert!(
line.contains(word),
"invented {word:?} from {line:?}: {kept:?}"
);
}
}
}
}
#[test]
fn the_note_and_the_hint_are_paid_for_before_the_prose_is_cut() {
let prose = "prose ".repeat(400);
let output = format!(
"{{\"ok\":false,\"error\":{{\"code\":\"runtime_error\",\"message\":\"{prose}\
MP4 H.264 encoder unavailable\"}}}}\n",
);
let message = run_failure(&failed(&output), RENDER, None);
assert!(message.contains("machine-side gap"), "got: {message}");
assert!(
message.len() <= MESSAGE_BUDGET_BYTES + '…'.len_utf8(),
"got {} bytes",
message.len()
);
let output = format!(
"{{\"ok\":false,\"error\":{{\"code\":\"runtime_error\",\"message\":\"{prose}\",\
\"hint\":\"compositions/scene.html:42 — intro is not defined. \
Try --docker for containerized rendering\"}}}}\n",
);
let message = run_failure(&failed(&output), RENDER, None);
assert!(
message.starts_with("runtime_error: prose"),
"the code and message still lead: {message}"
);
assert!(
message.contains("hint: compositions/scene.html:42"),
"got: {message}"
);
assert!(!message.contains("--docker"), "got: {message}");
assert!(
message.len() <= MESSAGE_BUDGET_BYTES + '…'.len_utf8(),
"got {} bytes",
message.len()
);
}
}