hex/src/capture_host/library.rs
Dax 2ac5e4b582
annotate: agent tools for captures (labs) (#2220)
* Annotate: agent tools that read a capture from the CLI

Adds Labs › Agent tools for captures (off by default, every OS, Annotate
group, labs.annotate_agent_tools) behind four new `hex annotate` commands
that run in the CLI process rather than over the control socket, so they
work with Hex closed and only read files and decode the bundle's video:

- `inspect [<capture>] [--marks] [--json]` prints summary.md, one line per
  mark (or No marks), scrawl.json pretty, or the marks as JSON.
- `zoom [<capture>] (--at <M:SS|secs|phrase> | --mark <n|id> [--frame N])
  [--span secs] [--frames N] [--full]` writes a dense sheet around a moment
  or a mark into <bundle>/zoom/ and prints its path, each cell's time, and
  what was said; a mark prints the mark's line first.
- `frames [<capture>] --from <M:SS|secs> --to <M:SS|secs> [--fps 4]` writes
  one PNG per frame and prints each path.
- `skill` prints the new skills/hex-annotate guide, installed with
  `npx skills add anomalyco/hex --skill hex-annotate`.

They reuse the engine's own primitives (zoom, agent_context, handoff,
sketch) and capture_host::library's bundle resolution, and leave everything
outside <bundle>/zoom/ alone. While the lab is off they refuse naming
`hex labs on annotate-agent-tools`; a build without the capture engine
answers unsupported like the other annotate commands.

Also adds the settings key to the registry, translations for the card, the
skill docs, docs/cli.md, the capture and labs feature maps, the maps'
checks and proof limits, and the four labs goldens the new card moves.

* Annotate agent tools: review fixes

- frames loads the bundle, clamps --to to its durationMs, and refuses a range
  over 240 frames with `invalid` (the count is (to - from) * fps / 1000 + 1),
  so one call can't write a whole recording; the cap is in the skill and both
  docs, and checked_range is tested at the cap, the clamp, and a start past
  the end.
- The hex-annotate skill no longer claims an Install action, says only
  inspect/zoom/frames take a bundle (skill takes none), shows a --mark run
  printing the mark line first with real curly-quoted Said lines, says frames
  falls back to frames/ keyframes without a video, and states the 240 cap.
- The Labs row takes the same Annotate policy lock as Copy a capture as one
  file.
- The capture() doc comment says the four agent reads run in the CLI process
  on every OS.
- crates/router parse_clock_ms multiplies and adds with checked arithmetic, so
  absurd minutes read as no time instead of overflowing; tested.

* Annotate agent tools: Annotate lock and clock bounds

- An organization's DisableAnnotate lock now covers the agent tools lab:
  labs_lock maps it to Lock::Annotate, switches(Lock::Annotate) includes its
  switch, and the gate reads off under the lock through a policy-parameterized
  annotate_agent_tools_under (the same shape as voice_prompt_under). The new
  policy test proves the managed card, setting_lock, the gate under a forced
  lock, enforce turning it off, and keep_saved leaving the saved switch alone.
- parse_clock_ms refuses NaN, infinities, negatives, and values at or past
  u64's range in both the M:SS and bare-seconds branches (seconds_ms), with
  the new 0:1e300, 1e300, 0:NaN, inf, and 0:-1 cases.
- docs/cli.md and the capture map note that frames extracts with ffmpeg from
  PATH when one is installed, as the engine already does.

* Annotate agent tools: count frames as the engine's decoder does

`frames` capped a range by (to - from) * fps / 1000 + 1, but the engine's
own decoder steps inclusively by max(1000 / fps, 1) ms, which asks for more
frames when fps doesn't divide 1000: 240 fps steps 4 ms, so 999 ms is 250
frames, not 240, and the cap let it through.

`checked_range` now counts frame_count's larger of the two formulas, so the
240-frame cap holds whichever decoder runs. The test adds 0-999 ms at
240 fps (refused: 250 frames) and 0-959 ms at 240 fps (allowed: exactly 240
frames, 231 at the rate), and the capture map states both counts.
2026-11-21 13:59:43 -05:00

231 lines
8.9 KiB
Rust

//! The captures folder as `hex capture list|show|send|route` read it. Reads
//! and explanations run on the control thread, off the listener; a send goes
//! through the `capture-route` thread so it orders with the capsule's.
use std::path::{Path, PathBuf};
use scrawl_capture::bundle::resolve_bundle_dir_in;
use scrawl_capture::delivery;
use scrawl_capture::model::{CaptureMode, ScrawlBundle};
use crate::control::{
ControlError, ControlReply, ScrawlCaptureDetail, ScrawlCaptureSession, ScrawlCaptureSummary,
};
/// How many captures `hex capture list` shows unless told.
const LIST: usize = 20;
pub fn list(limit: Option<usize>) -> Result<ControlReply, ControlError> {
let captures = captures_dir();
let entries = match std::fs::read_dir(&captures) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Ok(ControlReply::ScrawlCaptures {
captures: Vec::new(),
});
}
Err(error) => {
return Err(ControlError::new(
"internal",
format!("couldn't read {}: {error}", captures.display()),
));
}
};
let mut found: Vec<_> = entries
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|ext| ext == "scrawl") && path.is_dir())
// One still being written has no scrawl.json yet.
.filter_map(|path| load(&path).map(|bundle| summary(&path, &bundle)))
.collect();
found.sort_by_key(|summary| std::cmp::Reverse(summary.created_at_ms));
found.truncate(limit.unwrap_or(LIST));
Ok(ControlReply::ScrawlCaptures { captures: found })
}
pub fn show(capture: &str) -> Result<ControlReply, ControlError> {
let dir = resolve(capture)?;
let bundle = load(&dir).ok_or_else(|| unreadable(&dir))?;
let file = |name: &Option<String>| name.as_ref().map(|name| dir.join(name));
Ok(ControlReply::ScrawlCaptureDetail(Box::new(
ScrawlCaptureDetail {
summary: summary(&dir, &bundle),
window_title: bundle.target.window_title.clone(),
transcript: bundle.transcript.text.clone(),
note: bundle.note.clone(),
missing_transcript: bundle.transcript.missing.as_ref().map(|m| m.reason.clone()),
audio_stopped_at_ms: bundle.audio_stopped_at_ms,
marks: bundle.marks.len(),
keyframes: bundle.keyframes.len(),
video: file(&bundle.video),
audio: file(&bundle.audio),
contact_sheet: (!bundle.contact_sheet.is_empty())
.then(|| dir.join(&bundle.contact_sheet)),
},
)))
}
pub fn send(capture: &str, to: Option<String>, always: bool) -> Result<ControlReply, ControlError> {
let dir = resolve(capture)?;
if load(&dir).is_none() {
return Err(unreadable(&dir));
}
let message = super::routing::send_bundle(dir, to, always)
.map_err(|message| ControlError::new("failed", message))?;
Ok(ControlReply::Done {
message,
changed: true,
})
}
pub fn explain(capture: &str, ask_jev: bool) -> Result<ControlReply, ControlError> {
let dir = resolve(capture)?;
super::routing::router()
.run(|| scrawl_capture::routing::explain_bundle(&dir, None, ask_jev))
.map(|explanation| ControlReply::ScrawlCaptureRoute { explanation })
.map_err(|error| ControlError::new("failed", format!("{error:#}")))
}
fn captures_dir() -> PathBuf {
crate::app_settings::capture_settings().captures_dir()
}
/// A bundle name, path, or `latest`, inside the captures folder or not.
pub(super) fn resolve(capture: &str) -> Result<PathBuf, ControlError> {
resolve_bundle_dir_in(Some(&captures_dir()), Path::new(capture))
.map_err(|error| ControlError::new("not-found", format!("{error:#}")))
}
pub(super) fn load(dir: &Path) -> Option<ScrawlBundle> {
scrawl_capture::bundle::load_bundle_in(None, dir)
.ok()
.map(|(_, bundle)| bundle)
}
pub(super) fn unreadable(dir: &Path) -> ControlError {
ControlError::new(
"not-found",
format!("{} has no readable scrawl.json yet", dir.display()),
)
}
fn summary(dir: &Path, bundle: &ScrawlBundle) -> ScrawlCaptureSummary {
let mode = if bundle.source.as_deref() == Some("iphone") {
"iphone"
} else {
match bundle.target.mode {
CaptureMode::Display => "screen",
CaptureMode::Window => "window",
CaptureMode::Region => "area",
CaptureMode::Device => "iphone",
}
};
ScrawlCaptureSummary {
id: dir
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default(),
bundle: dir.to_path_buf(),
created_at_ms: bundle.created_at_ms,
duration_ms: bundle.duration_ms,
mode: mode.into(),
app: bundle.target.app.clone(),
words: scrawl_capture::transcribe::word_count(&bundle.transcript),
sent_to: bundle
.destination
.as_ref()
.map(|dest| ScrawlCaptureSession {
session: dest.session.clone(),
title: dest.title.clone(),
}),
queued: dir.join(delivery::PENDING).exists(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_capture_on_disk_summarizes_its_mode_words_and_send() {
let root = std::env::temp_dir().join(format!(
"hex-capture-library-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let dir = root.join("1792933491953.scrawl");
std::fs::create_dir_all(&dir).unwrap();
assert!(load(&dir).is_none(), "nothing written yet");
let frame = r#"{"x":0,"y":0,"width":1,"height":1,"scale":2}"#;
let manifest = format!(
r#"{{"version":1,"id":"a","createdAtMs":1792933491953,"durationMs":4000,
"target":{{"mode":"window","app":"Brave","displayId":1,"frame":{frame}}},
"transcript":{{"source":"parakeet","text":"make it blue","segments":[],
"words":[{{"text":"make","t0":0,"t1":1}},{{"text":"it","t0":1,"t1":2}},
{{"text":"blue","t0":2,"t1":3}}]}},
"strokes":[],"marks":[],"events":[],"keyframes":[],"contactSheet":"sheet.jpg",
"destination":{{"session":"ses_1","title":"Hex","via":"chosen"}}}}"#
);
std::fs::write(dir.join("scrawl.json"), manifest).unwrap();
std::fs::write(dir.join(delivery::PENDING), "{}").unwrap();
let resolved = resolve(dir.to_str().unwrap()).unwrap();
let bundle = load(&resolved).expect("the manifest reads");
let summary = summary(&resolved, &bundle);
assert_eq!(summary.id, "1792933491953.scrawl");
assert_eq!(summary.mode, "window");
assert_eq!(summary.app.as_deref(), Some("Brave"));
assert_eq!(summary.words, 3);
assert_eq!(
summary.sent_to,
Some(ScrawlCaptureSession {
session: "ses_1".into(),
title: "Hex".into()
})
);
assert!(summary.queued);
assert_eq!(
resolve(root.join("missing.scrawl").to_str().unwrap())
.unwrap_err()
.code,
"not-found"
);
let _ = std::fs::remove_dir_all(root);
}
/// A model that gives no word times (GigaAM v3) said every word in the
/// text, so the list counts them and the capture never reads as silence.
#[test]
fn a_capture_without_word_times_counts_the_words_it_says() {
let root = std::env::temp_dir().join(format!(
"hex-capture-untimed-{}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let frame = r#"{"x":0,"y":0,"width":1,"height":1,"scale":2}"#;
let write = |name: &str, text: &str| {
let dir = root.join(name);
std::fs::create_dir_all(&dir).unwrap();
let manifest = format!(
r#"{{"version":1,"id":"a","createdAtMs":1792933491953,"durationMs":4000,
"target":{{"mode":"display","displayId":1,"frame":{frame}}},
"transcript":{{"source":"hex","text":"{text}","segments":[],"words":[]}},
"strokes":[],"marks":[],"events":[],"keyframes":[],"contactSheet":"sheet.jpg"}}"#
);
std::fs::write(dir.join("scrawl.json"), manifest).unwrap();
let bundle = load(&dir).expect("the manifest reads");
summary(&dir, &bundle).words
};
assert_eq!(write("1792933491953.scrawl", " make it blue "), 3);
assert_eq!(
write("1792933491954.scrawl", " "),
0,
"silence counts none"
);
let _ = std::fs::remove_dir_all(root);
}
}