Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: require explicit recording benchmark invocation

Richie McIlroy45369c54b951
diff --git a/apps/desktop/scripts/stop-editor-performance.md b/apps/desktop/scripts/stop-editor-performance.md
index 48b51e0a8..0ddc230c3 100644
--- a/apps/desktop/scripts/stop-editor-performance.md
+++ b/apps/desktop/scripts/stop-editor-performance.md
@@ -522,7 +522,7 @@ From `apps/desktop-gpui`, build the drivers with `cargo build --example studio-f
`CAP_BENCH_FULL_AUDIO_ONLY=1` skips the range experiment. Without it, the driver exits unsuccessfully if decoded ranges differ from the full-track reference. `CAP_BENCH_STREAM_AUDIO=1` also checks every sequential chunk against that reference. Preserve failed range experiments as failures; the known two-hour timestamp-seeking mismatch must not be mistaken for passing progressive-window coverage. Progressive windows use sequential sample positions instead.
-The debug Tauri driver is enabled by `CAP_STOP_EDITOR_BENCHMARK_OUTPUT`, with `CAP_STOP_BENCH_SECONDS`, optional `CAP_STOP_BENCH_MIC`, and optional `CAP_STOP_BENCH_SYSTEM_AUDIO`. Use an isolated app identifier and recordings directory. Its injected editor observer waits for a completed render in the existing frame statistics, a visible editor canvas, and two animation frames. A timeout is a failed benchmark, not a successful editor-open measurement. The initial observer only watched worker messages and missed Tauri's direct-canvas renderer; that incomplete run is excluded.
+The debug Tauri driver requires the explicit arguments `--stop-editor-benchmark --allow-real-recording`, both `CAP_STOP_EDITOR_BENCHMARK_OUTPUT` and `CAP_STOP_BENCH_LOG_DIR`, and a private app identifier beginning `so.cap.desktop.stop-editor-benchmark.` with a nonempty suffix. Output and log paths must be fresh private siblings under an existing canonical directory. `CAP_STOP_BENCH_SECONDS` selects 1–86,400 seconds (default 15); `CAP_STOP_BENCH_MIC` and `CAP_STOP_BENCH_SYSTEM_AUDIO` opt into audio. Environment variables alone cannot activate recording. Keep the private identifier and recordings directory isolated from the user library. Its injected editor observer waits for a completed render in the existing frame statistics, a visible editor canvas, and two animation frames. A timeout is a failed benchmark, not a successful editor-open measurement. The initial observer only watched worker messages and missed Tauri's direct-canvas renderer; that incomplete run is excluded.
Existing GPUI drivers include `CAP_GPUI_AUTO_RECORD=studio:60`, `CAP_GPUI_AUTO_NO_MIC=1`, `CAP_GPUI_AUTO_SYSTEM_AUDIO=1`, `CAP_GPUI_AUTO_EDITOR`, and `CAP_GPUI_AUTO_PLAYBACK`. `CAP_GPUI_AUTO_SEEK` targets a fraction of the visible timeline viewport. The new `CAP_GPUI_AUTO_SEEK_TIME=7194.5` targets seconds into the recording and logs the clamped time passed to the ordinary seek method. Use explicit time for long-recording tail checks. Keep app data and recordings isolated from the user's library.
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 17447ba4a..ef91be562 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -6525,6 +6525,13 @@ type FilteredRegistry = tracing_subscriber::layer::Layered<
pub type DynLoggingLayer = Box<dyn tracing_subscriber::Layer<FilteredRegistry> + Send + Sync>;
type LoggingHandle = tracing_subscriber::reload::Handle<Option<DynLoggingLayer>, FilteredRegistry>;
+#[cfg(debug_assertions)]
+pub fn initialize_stop_editor_benchmark(
+ create_log_directory: impl FnOnce(&std::path::Path, &std::path::Path) -> std::io::Result<PathBuf>,
+) -> Result<Option<PathBuf>, String> {
+ stop_editor_benchmark::initialize(create_log_directory)
+}
+
/// Software recovery exists to break GPU-driver crash loops: a process that died
/// while wgpu adapter/device initialisation was in flight. Any other unexpected
/// termination (force-quit, power loss, OS kill, a hung shutdown) says nothing
@@ -7075,6 +7082,8 @@ pub async fn run(recording_logging_handle: LoggingHandle, logs_dir: PathBuf) {
})
.setup(move |app| {
let app = app.handle().clone();
+ #[cfg(debug_assertions)]
+ stop_editor_benchmark::validate_app_identifier(&app.config().identifier)?;
#[cfg(target_os = "macos")]
let _startup_open_guard = app
.try_state::<StartupOpenGate>()
diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs
index 7ae1d7052..16b442384 100644
--- a/apps/desktop/src-tauri/src/main.rs
+++ b/apps/desktop/src-tauri/src/main.rs
@@ -101,22 +101,15 @@ fn main() {
.join("logs");
#[cfg(debug_assertions)]
- let path = match (
- std::env::var_os("CAP_STOP_EDITOR_BENCHMARK_OUTPUT"),
- std::env::var_os("CAP_STOP_BENCH_LOG_DIR"),
- ) {
- (Some(output), Some(directory)) => match create_benchmark_log_directory(
- std::path::Path::new(&output),
- std::path::Path::new(&directory),
- ) {
- Ok(directory) => directory,
+ let path =
+ match cap_desktop_lib::initialize_stop_editor_benchmark(create_benchmark_log_directory)
+ {
+ Ok(directory) => directory.unwrap_or(path),
Err(error) => {
- eprintln!("Invalid private benchmark log directory: {error}");
+ eprintln!("Invalid Stop benchmark invocation: {error}");
std::process::exit(2);
}
- },
- _ => path,
- };
+ };
path
};
diff --git a/apps/desktop/src-tauri/src/stop_editor_benchmark.rs b/apps/desktop/src-tauri/src/stop_editor_benchmark.rs
index b8c11c198..303558cbf 100644
--- a/apps/desktop/src-tauri/src/stop_editor_benchmark.rs
+++ b/apps/desktop/src-tauri/src/stop_editor_benchmark.rs
@@ -1,4 +1,5 @@
use std::{
+ ffi::OsString,
path::{Path, PathBuf},
sync::{
Arc, Mutex, OnceLock,
@@ -14,20 +15,184 @@ pub const SCRIPT: &str = include_str!("stop-editor-benchmark.js");
pub const DOM_SCRIPT: &str = include_str!("stop-editor-parity-dom.js");
static FRAME_CAPTURE: OnceLock<Mutex<FrameCapture>> = OnceLock::new();
static STARTED: AtomicBool = AtomicBool::new(false);
+static CONFIG: OnceLock<Result<Option<BenchmarkConfig>, String>> = OnceLock::new();
+static APP_ADMITTED: AtomicBool = AtomicBool::new(false);
+
+struct BenchmarkConfig {
+ output: PathBuf,
+ log_directory: PathBuf,
+ seconds: u64,
+ microphone: Option<String>,
+ system_audio: bool,
+ fixture_window: bool,
+ frame_directory: Option<PathBuf>,
+ dom_capture: bool,
+}
+
+fn parse_config(
+ arguments: impl IntoIterator<Item = OsString>,
+ mut environment: impl FnMut(&'static str) -> Option<OsString>,
+) -> Result<Option<BenchmarkConfig>, String> {
+ let arguments: Vec<_> = arguments.into_iter().collect();
+ let benchmark = arguments
+ .iter()
+ .filter(|arg| *arg == "--stop-editor-benchmark")
+ .count();
+ let recording = arguments
+ .iter()
+ .filter(|arg| *arg == "--allow-real-recording")
+ .count();
+ if benchmark == 0 && recording == 0 {
+ return Ok(None);
+ }
+ if arguments.len() != 2 || benchmark != 1 || recording != 1 {
+ return Err(
+ "Benchmark invocation requires exactly --stop-editor-benchmark --allow-real-recording"
+ .into(),
+ );
+ }
+ let output = environment("CAP_STOP_EDITOR_BENCHMARK_OUTPUT")
+ .filter(|value| !value.is_empty())
+ .ok_or("Benchmark invocation requires CAP_STOP_EDITOR_BENCHMARK_OUTPUT")?;
+ let log_directory = environment("CAP_STOP_BENCH_LOG_DIR")
+ .filter(|value| !value.is_empty())
+ .ok_or("Benchmark invocation requires CAP_STOP_BENCH_LOG_DIR")?;
+ let seconds = environment("CAP_STOP_BENCH_SECONDS")
+ .map(|value| {
+ value
+ .into_string()
+ .map_err(|_| "Benchmark duration must be valid UTF-8".to_string())?
+ .parse::<u64>()
+ .map_err(|_| "Benchmark duration must be a whole number of seconds".to_string())
+ })
+ .transpose()?
+ .unwrap_or(15);
+ if !(1..=86_400).contains(&seconds) {
+ return Err("Benchmark duration must be between 1 and 86400 seconds".into());
+ }
+ let microphone = environment("CAP_STOP_BENCH_MIC")
+ .map(|value| {
+ value
+ .into_string()
+ .map_err(|_| "Benchmark microphone must be valid UTF-8".to_string())
+ .and_then(|value| {
+ if value.is_empty() {
+ Err("Benchmark microphone must not be empty".into())
+ } else {
+ Ok(value)
+ }
+ })
+ })
+ .transpose()?;
+ Ok(Some(BenchmarkConfig {
+ output: PathBuf::from(output),
+ log_directory: PathBuf::from(log_directory),
+ seconds,
+ microphone,
+ system_audio: environment("CAP_STOP_BENCH_SYSTEM_AUDIO").is_some(),
+ fixture_window: environment("CAP_STOP_BENCH_FIXTURE_WINDOW").is_some(),
+ frame_directory: environment("CAP_STOP_BENCH_FRAME_DIR").map(PathBuf::from),
+ dom_capture: environment("CAP_STOP_BENCH_DOM_CAPTURE").is_some(),
+ }))
+}
+
+fn validate_frame_directory(config: &BenchmarkConfig) -> Result<(), String> {
+ let Some(directory) = config.frame_directory.as_ref() else {
+ return Ok(());
+ };
+ if !directory.is_absolute()
+ || directory == &config.output
+ || directory == &config.log_directory
+ || directory.components().any(|component| {
+ !matches!(
+ component,
+ std::path::Component::Prefix(_)
+ | std::path::Component::RootDir
+ | std::path::Component::Normal(_)
+ )
+ })
+ {
+ return Err(
+ "Benchmark frame directory must be a distinct absolute path without traversal".into(),
+ );
+ }
+ let parent = directory
+ .parent()
+ .ok_or("Benchmark frame directory has no parent")?;
+ if parent.canonicalize().map_err(|error| error.to_string())? != parent || !parent.is_dir() {
+ return Err("Benchmark frame directory requires an existing canonical parent".into());
+ }
+ match std::fs::symlink_metadata(directory) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.to_string()),
+ Ok(_) => Err("Benchmark frame directory must be new".into()),
+ }
+}
+
+fn prepare_config(
+ config: Option<BenchmarkConfig>,
+ create_log_directory: impl FnOnce(&Path, &Path) -> std::io::Result<PathBuf>,
+) -> Result<Option<BenchmarkConfig>, String> {
+ if let Some(config) = config.as_ref() {
+ validate_frame_directory(config)?;
+ create_log_directory(&config.output, &config.log_directory)
+ .map_err(|error| error.to_string())?;
+ }
+ Ok(config)
+}
+
+pub fn initialize(
+ create_log_directory: impl FnOnce(&Path, &Path) -> std::io::Result<PathBuf>,
+) -> Result<Option<PathBuf>, String> {
+ match CONFIG.get_or_init(|| {
+ let config = parse_config(std::env::args_os().skip(1), std::env::var_os)?;
+ prepare_config(config, create_log_directory)
+ }) {
+ Ok(config) => Ok(config.as_ref().map(|config| config.log_directory.clone())),
+ Err(error) => Err(error.clone()),
+ }
+}
+
+fn config() -> Option<&'static BenchmarkConfig> {
+ CONFIG.get()?.as_ref().ok()?.as_ref()
+}
+
+fn admit_identifier(requested: bool, identifier: &str) -> Result<bool, String> {
+ if !requested {
+ return Ok(false);
+ }
+ if identifier
+ .strip_prefix("so.cap.desktop.stop-editor-benchmark.")
+ .is_some_and(|suffix| !suffix.is_empty())
+ {
+ Ok(true)
+ } else {
+ Err("Benchmark invocation requires a private benchmark app identifier".into())
+ }
+}
+
+pub fn validate_app_identifier(identifier: &str) -> Result<(), String> {
+ let admitted = admit_identifier(config().is_some(), identifier)?;
+ APP_ADMITTED.store(admitted, Ordering::SeqCst);
+ Ok(())
+}
pub fn enabled() -> bool {
- std::env::var_os("CAP_STOP_EDITOR_BENCHMARK_OUTPUT").is_some()
+ APP_ADMITTED.load(Ordering::SeqCst) && config().is_some()
}
pub fn run(app: tauri::AppHandle) {
- let Some(output) = std::env::var_os("CAP_STOP_EDITOR_BENCHMARK_OUTPUT") else {
+ if !enabled() {
+ return;
+ }
+ let Some(config) = config() else {
return;
};
if STARTED.swap(true, Ordering::SeqCst) {
return;
}
tokio::spawn(async move {
- let result = measure(&app).await;
+ let result = measure(&app, config).await;
let mut value = match result {
Ok(value) => value,
Err(error) => serde_json::json!({ "error": error }),
@@ -40,28 +205,26 @@ pub fn run(app: tauri::AppHandle) {
serde_json::json!({ "status": "incomplete", "error": error })
}
}
- if let Err(error) = std::fs::write(output, value.to_string()) {
+ if let Err(error) = std::fs::write(&config.output, value.to_string()) {
tracing::error!(%error, "Could not write Stop benchmark results");
}
});
}
-async fn measure(app: &tauri::AppHandle) -> Result<serde_json::Value, String> {
+async fn measure(
+ app: &tauri::AppHandle,
+ config: &BenchmarkConfig,
+) -> Result<serde_json::Value, String> {
tokio::time::sleep(Duration::from_secs(3)).await;
let state = app.state::<Arc<RwLock<crate::App>>>();
- crate::set_mic_input(
- app.clone(),
- state.clone(),
- std::env::var("CAP_STOP_BENCH_MIC").ok(),
- )
- .await?;
- let capture_target = benchmark_capture_target()?;
+ crate::set_mic_input(app.clone(), state.clone(), config.microphone.clone()).await?;
+ let capture_target = benchmark_capture_target(config.fixture_window)?;
let action = crate::recording::start_recording(
app.clone(),
state.clone(),
crate::recording::StartRecordingInputs {
capture_target,
- capture_system_audio: std::env::var_os("CAP_STOP_BENCH_SYSTEM_AUDIO").is_some(),
+ capture_system_audio: config.system_audio,
mode: cap_recording::RecordingMode::Studio,
organization_id: None,
},
@@ -70,10 +233,7 @@ async fn measure(app: &tauri::AppHandle) -> Result<serde_json::Value, String> {
if !matches!(action, crate::recording::RecordingAction::Started) {
return Err("Benchmark recording did not start".into());
}
- let seconds = std::env::var("CAP_STOP_BENCH_SECONDS")
- .ok()
- .and_then(|value| value.parse().ok())
- .unwrap_or(15);
+ let seconds = config.seconds;
tokio::time::sleep(Duration::from_secs(seconds)).await;
let project = state
.read()
@@ -117,10 +277,11 @@ async fn measure(app: &tauri::AppHandle) -> Result<serde_json::Value, String> {
Ok(result)
}
-fn benchmark_capture_target() -> Result<cap_recording::screen_capture::ScreenCaptureTarget, String>
-{
+fn benchmark_capture_target(
+ fixture_window: bool,
+) -> Result<cap_recording::screen_capture::ScreenCaptureTarget, String> {
use cap_recording::screen_capture::ScreenCaptureTarget;
- if std::env::var_os("CAP_STOP_BENCH_FIXTURE_WINDOW").is_none() {
+ if !fixture_window {
return Ok(ScreenCaptureTarget::Display {
id: scap_targets::Display::primary().id(),
});
@@ -149,11 +310,11 @@ fn select_exact_fixture<T>(
}
pub fn frame_capture_requested() -> bool {
- enabled() && std::env::var_os("CAP_STOP_BENCH_FRAME_DIR").is_some()
+ enabled() && config().is_some_and(|config| config.frame_directory.is_some())
}
pub fn dom_capture_requested() -> bool {
- enabled() && std::env::var_os("CAP_STOP_BENCH_DOM_CAPTURE").is_some()
+ enabled() && config().is_some_and(|config| config.dom_capture)
}
#[derive(Clone, Copy)]
@@ -195,7 +356,7 @@ impl FrameCapture {
}
fn arm_frame_capture(app: &tauri::AppHandle, project: Option<&Path>) -> Result<(), String> {
- let Some(directory) = std::env::var_os("CAP_STOP_BENCH_FRAME_DIR") else {
+ let Some(directory) = config().and_then(|config| config.frame_directory.as_ref()) else {
return Ok(());
};
if !app
@@ -205,7 +366,7 @@ fn arm_frame_capture(app: &tauri::AppHandle, project: Option<&Path>) -> Result<(
{
return Err("Frame capture requires a private benchmark app identifier".into());
}
- let directory = PathBuf::from(directory);
+ let directory = directory.clone();
if !directory.is_absolute() {
return Err("Frame capture directory must be absolute".into());
}
@@ -388,6 +549,190 @@ impl Drop for DomCapture {
}
}
+#[cfg(test)]
+mod invocation_tests {
+ use super::*;
+
+ fn request(settings: &[(&str, &str)]) -> Result<Option<BenchmarkConfig>, String> {
+ parse_config(
+ ["--stop-editor-benchmark", "--allow-real-recording"].map(OsString::from),
+ |name| {
+ settings
+ .iter()
+ .find(|(key, _)| *key == name)
+ .map(|(_, value)| OsString::from(*value))
+ },
+ )
+ }
+
+ fn settings() -> [(&'static str, &'static str); 2] {
+ [
+ ("CAP_STOP_EDITOR_BENCHMARK_OUTPUT", "/benchmark/result.json"),
+ ("CAP_STOP_BENCH_LOG_DIR", "/benchmark/logs"),
+ ]
+ }
+
+ #[test]
+ fn ordinary_arguments_never_read_benchmark_environment_or_create_logs() {
+ for arguments in [
+ vec![],
+ vec!["recording.cap"],
+ vec!["--stop-editor-benchmark=true"],
+ vec!["https://example.invalid/--allow-real-recording"],
+ ] {
+ let config = parse_config(arguments.into_iter().map(OsString::from), |_| {
+ panic!("Ordinary startup must not read benchmark environment")
+ })
+ .unwrap();
+ assert!(
+ prepare_config(config, |_, _| {
+ panic!("Ordinary startup must not create benchmark logs")
+ })
+ .unwrap()
+ .is_none()
+ );
+ }
+ }
+
+ #[test]
+ fn incomplete_or_mixed_invocations_fail_before_reading_settings() {
+ for arguments in [
+ vec!["--stop-editor-benchmark"],
+ vec!["--allow-real-recording"],
+ vec![
+ "--stop-editor-benchmark",
+ "--stop-editor-benchmark",
+ "--allow-real-recording",
+ ],
+ vec![
+ "--stop-editor-benchmark",
+ "--allow-real-recording",
+ "recording.cap",
+ ],
+ vec!["--", "--stop-editor-benchmark", "--allow-real-recording"],
+ ] {
+ assert!(
+ parse_config(arguments.into_iter().map(OsString::from), |_| {
+ panic!("Malformed invocation must fail before reading settings")
+ })
+ .is_err()
+ );
+ }
+ }
+
+ #[test]
+ fn explicit_invocation_requires_both_private_paths() {
+ assert!(request(&[]).is_err());
+ assert!(request(&settings()[..1]).is_err());
+ assert!(request(&settings()[1..]).is_err());
+ for missing in ["CAP_STOP_EDITOR_BENCHMARK_OUTPUT", "CAP_STOP_BENCH_LOG_DIR"] {
+ let mut settings = settings();
+ for (name, value) in &mut settings {
+ if *name == missing {
+ *value = "";
+ }
+ }
+ assert!(request(&settings).is_err());
+ }
+ }
+
+ #[test]
+ fn explicit_invocation_retains_default_duration_and_capture_options() {
+ let config = request(&settings()).unwrap().unwrap();
+ assert_eq!(config.seconds, 15);
+ assert_eq!(config.output, Path::new("/benchmark/result.json"));
+ assert_eq!(config.log_directory, Path::new("/benchmark/logs"));
+ assert!(config.microphone.is_none());
+ assert!(!config.system_audio);
+ assert!(!config.fixture_window);
+ assert!(config.frame_directory.is_none());
+ assert!(!config.dom_capture);
+ }
+
+ #[test]
+ fn explicit_invocation_freezes_all_capture_settings() {
+ let mut settings = settings().to_vec();
+ settings.extend([
+ ("CAP_STOP_BENCH_SECONDS", "7200"),
+ ("CAP_STOP_BENCH_MIC", "Test microphone"),
+ ("CAP_STOP_BENCH_SYSTEM_AUDIO", "1"),
+ ("CAP_STOP_BENCH_FIXTURE_WINDOW", "1"),
+ ("CAP_STOP_BENCH_FRAME_DIR", "/benchmark/frames"),
+ ("CAP_STOP_BENCH_DOM_CAPTURE", "1"),
+ ]);
+ let config = request(&settings).unwrap().unwrap();
+ assert_eq!(config.seconds, 7200);
+ assert_eq!(config.microphone.as_deref(), Some("Test microphone"));
+ assert!(config.system_audio);
+ assert!(config.fixture_window);
+ assert_eq!(
+ config.frame_directory.as_deref(),
+ Some(Path::new("/benchmark/frames"))
+ );
+ assert!(config.dom_capture);
+ }
+
+ #[test]
+ fn invalid_duration_or_microphone_is_not_replaced_with_a_recording_default() {
+ for value in [
+ "",
+ "invalid",
+ "-1",
+ "1.5",
+ "0",
+ "86401",
+ "18446744073709551616",
+ ] {
+ let mut settings = settings().to_vec();
+ settings.push(("CAP_STOP_BENCH_SECONDS", value));
+ assert!(request(&settings).is_err());
+ }
+ let mut settings = settings().to_vec();
+ settings.push(("CAP_STOP_BENCH_MIC", ""));
+ assert!(request(&settings).is_err());
+ }
+
+ #[test]
+ fn configured_invocation_must_pass_the_private_log_validator() {
+ let config = request(&settings()).unwrap();
+ let mut calls = 0;
+ let prepared = prepare_config(config, |output, directory| {
+ calls += 1;
+ assert_eq!(output, Path::new("/benchmark/result.json"));
+ assert_eq!(directory, Path::new("/benchmark/logs"));
+ Ok(directory.to_path_buf())
+ })
+ .unwrap();
+ assert_eq!(calls, 1);
+ assert!(prepared.is_some());
+ assert!(
+ prepare_config(request(&settings()).unwrap(), |_, _| {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::AlreadyExists,
+ "retained evidence",
+ ))
+ })
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn app_admission_rejects_normal_and_empty_private_identifiers() {
+ for identifier in [
+ "so.cap.desktop",
+ "so.cap.desktop.dev",
+ "so.cap.desktop.stop-editor-benchmark.",
+ "other.so.cap.desktop.stop-editor-benchmark.test",
+ ] {
+ assert!(!admit_identifier(false, identifier).unwrap());
+ assert!(admit_identifier(true, identifier).is_err());
+ }
+ let private = "so.cap.desktop.stop-editor-benchmark.test";
+ assert!(!admit_identifier(false, private).unwrap());
+ assert!(admit_identifier(true, private).unwrap());
+ }
+}
+
#[cfg(test)]
mod parity_capture_tests {
use super::*;