diff --git a/CLAUDE.md b/CLAUDE.md index 8e6ad315..25080d25 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,6 +51,9 @@ Do not pipe pytest through `| tail -N` if you want streaming output; it buffers - Test command: `bash test` or targeted subsets above. - Prefer native Rust implementations and fail-loud behavior over silent Python fallbacks. - Do not add backwards-compat hacks for code paths that no longer exist. +- For deterministic in-product render checks, use `fastled --test` + with the `--test-*` screenshot, interval, log, and timeout flags. This uses + the shipped Tauri viewer and exits automatically; no browser harness is needed. ## Common Gotchas diff --git a/Cargo.lock b/Cargo.lock index 922fd623..b4818abb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1167,6 +1167,7 @@ dependencies = [ "dirs 5.0.1", "flate2", "fs2", + "getrandom 0.3.4", "globset", "indexmap 1.9.3", "notify", diff --git a/README.md b/README.md index 9eaeb919..b01c0720 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,28 @@ Useful flags: Set `FASTLED_VIEWER_LOGS=1` to forward the viewer window's browser console output (`console.*`, uncaught errors, failed fetches) to the terminal's stderr, prefixed with `[viewer]` — useful when diagnosing a blank or broken viewer. +### Testing your sketch from CI or an agent + +The shipped viewer can render a sketch, capture its canvas, collect browser +logs, and exit without Playwright or a separate browser installation: + +```bash +fastled examples/Blink --test --test-wait-secs=2 \ + --test-screenshot=out/blink.png --test-log=out/blink.viewer.log \ + --test-exit-on-error +``` + +For a frame sequence, add +`--test-interval-secs=0.5 --test-count=10` and use a path such as +`out/blink-{n:03}.png`. The interval is the target between scheduled capture +starts; slow canvas readback or uploads can delay later frames. The wait begins +only after the compiled page has a canvas and two animation frames have +elapsed. Exit codes are `0` for success, +`1` for compile/viewer/I/O failure, `2` for a captured page error when +`--test-exit-on-error` is enabled, `124` for the total timeout, and `125` for +the ready timeout. An interrupted run exits `130`. The viewer and local server +are stopped automatically. + ## Features ### Browser Compatibility diff --git a/crates/fastled-cli/Cargo.toml b/crates/fastled-cli/Cargo.toml index 913c031a..63c1efda 100644 --- a/crates/fastled-cli/Cargo.toml +++ b/crates/fastled-cli/Cargo.toml @@ -48,6 +48,7 @@ tempfile = "3" zccache-fingerprint = { workspace = true } shell-words = { workspace = true } globset = { workspace = true } +getrandom = "0.3" [build-dependencies] indexmap = { version = "1.9.3", features = ["std"] } diff --git a/crates/fastled-cli/src/cli.rs b/crates/fastled-cli/src/cli.rs index 4e43bdc6..f6cd50d5 100644 --- a/crates/fastled-cli/src/cli.rs +++ b/crates/fastled-cli/src/cli.rs @@ -1,3 +1,5 @@ +use std::path::PathBuf; + use clap::{Parser, Subcommand, ValueEnum}; #[derive(Clone, Debug, Subcommand)] @@ -111,6 +113,82 @@ pub(crate) struct Cli { #[arg(long)] pub(crate) no_https: bool, + /// Compile, render, collect requested test artifacts, and exit. + #[arg(long, conflicts_with_all = ["just_compile", "no_app"], help_heading = "Production testing")] + pub(crate) test: bool, + + /// Seconds to wait after the sketch is ready before the first capture. + #[arg( + long, + default_value_t = 1.0, + requires = "test", + help_heading = "Production testing" + )] + pub(crate) test_wait_secs: f64, + + /// PNG output path. Interval mode supports an unpadded index, {n:03}, and {ts}. + #[arg( + long, + value_name = "PATH", + requires = "test", + verbatim_doc_comment, + help_heading = "Production testing" + )] + pub(crate) test_screenshot: Option, + + /// Target interval between scheduled capture starts; slow captures may delay later frames. + #[arg(long, requires = "test", help_heading = "Production testing")] + pub(crate) test_interval_secs: Option, + + /// Number of screenshots to take in interval mode. + #[arg( + long, + requires = "test", + conflicts_with = "test_duration_secs", + help_heading = "Production testing" + )] + pub(crate) test_count: Option, + + /// Total capture window in seconds for interval mode. + #[arg( + long, + requires = "test", + conflicts_with = "test_count", + help_heading = "Production testing" + )] + pub(crate) test_duration_secs: Option, + + /// Append viewer console and error output to this file. + #[arg( + long, + value_name = "PATH", + requires = "test", + help_heading = "Production testing" + )] + pub(crate) test_log: Option, + + /// Exit with code 2 when the viewer reports a page-side error. + #[arg(long, requires = "test", help_heading = "Production testing")] + pub(crate) test_exit_on_error: bool, + + /// Hard upper bound in seconds for compile, ready wait, and capture. + #[arg( + long, + default_value_t = 120.0, + requires = "test", + help_heading = "Production testing" + )] + pub(crate) test_timeout_secs: f64, + + /// Seconds to wait for a rendered canvas after compilation succeeds. + #[arg( + long, + default_value_t = 15.0, + requires = "test", + help_heading = "Production testing" + )] + pub(crate) test_ready_timeout_secs: f64, + /// Use the latest tagged FastLED release when initialising examples with --init. /// Defaults to `master`; tagged releases older than the meson migration cannot be built. #[arg(long)] @@ -181,6 +259,12 @@ pub(crate) fn validate_init_ref_flags(cli: &Cli) -> Result<(), &'static str> { Ok(()) } +pub(crate) fn apply_test_implications(cli: &mut Cli) { + if cli.test { + cli.no_interactive = true; + } +} + pub(crate) fn requested_init_ref(cli: &Cli) -> Option<&str> { if cli.latest { // `--latest` opts into the most recent tagged FastLED release. The @@ -202,6 +286,7 @@ pub(crate) fn requested_init_ref(cli: &Cli) -> Option<&str> { #[cfg(test)] mod tests { use super::*; + use clap::CommandFactory; #[test] fn clangd_emission_is_opt_in() { @@ -235,4 +320,67 @@ mod tests { }) )); } + + #[test] + fn production_test_flags_parse_as_a_group() { + let cli = Cli::parse_from([ + "fastled", + "sketch", + "--test", + "--test-wait-secs=2", + "--test-interval-secs=0.5", + "--test-count=10", + "--test-screenshot=out-{n:03}.png", + "--test-log=run.log", + "--test-exit-on-error", + ]); + assert!(cli.test); + assert_eq!(cli.test_wait_secs, 2.0); + assert_eq!(cli.test_interval_secs, Some(0.5)); + assert_eq!(cli.test_count, Some(10)); + assert_eq!(cli.test_screenshot, Some(PathBuf::from("out-{n:03}.png"))); + assert_eq!(cli.test_log, Some(PathBuf::from("run.log"))); + assert!(cli.test_exit_on_error); + } + + #[test] + fn production_test_help_describes_filename_templates() { + let help = Cli::command().render_long_help().to_string(); + assert!(help.contains("supports an unpadded index, {n:03}, and {ts}")); + assert!(help.contains("Target interval between scheduled capture starts")); + } + + #[test] + fn test_mode_implies_non_interactive_before_directory_resolution() { + let mut cli = Cli::parse_from(["fastled", "--test"]); + assert!(!cli.no_interactive); + apply_test_implications(&mut cli); + assert!(cli.no_interactive); + } + + #[test] + fn production_test_suboptions_require_master_switch() { + assert!(Cli::try_parse_from([ + "fastled", + "sketch", + "--test-count=2", + "--test-interval-secs=.5", + "--test-screenshot=out-{n}.png" + ]) + .is_err()); + } + + #[test] + fn production_test_count_and_duration_conflict() { + assert!(Cli::try_parse_from([ + "fastled", + "sketch", + "--test", + "--test-count=2", + "--test-duration-secs=1", + "--test-interval-secs=.5", + "--test-screenshot=out-{n}.png" + ]) + .is_err()); + } } diff --git a/crates/fastled-cli/src/commands.rs b/crates/fastled-cli/src/commands.rs index aa51a5f7..9e76c629 100644 --- a/crates/fastled-cli/src/commands.rs +++ b/crates/fastled-cli/src/commands.rs @@ -1,9 +1,13 @@ +use std::collections::{HashMap, HashSet}; +use std::fs::{File, OpenOptions}; +use std::io::Write; use std::path::PathBuf; use std::process::ExitCode; use std::sync::{Arc, RwLock}; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; use crate::build; -use crate::cli::{requested_init_ref, validate_init_ref_flags, Cli}; +use crate::cli::{requested_init_ref, validate_init_ref_flags, Cli, LinkMode}; use crate::compile_stream::{ announce_link_mode, ensure_compile_prerequisites, purge_fastled_cache, report_build_outcome, run_native_compile_streaming, selected_build_mode, send_sse, write_build_status, @@ -17,6 +21,7 @@ use crate::path::NormalizedPath; use crate::project; use crate::selection::prompt_for_example; use crate::server; +use crate::test_mode::{self, TestOutcome}; use crate::viewer; use crate::watcher; @@ -71,6 +76,7 @@ pub(crate) fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode { 0, Some(tx.clone()), debug_symbols.clone(), + None, ) .await { @@ -195,6 +201,308 @@ pub(crate) fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode { }) } +/// Compile once, render in the shipped Tauri viewer, collect deterministic +/// test artifacts, and tear the contained viewer/server processes down. +pub(crate) fn compile_and_test(dir: &str, cli: &Cli) -> ExitCode { + let started = Instant::now(); + let plan = match test_mode::build_test_plan(cli) { + Ok(plan) => plan, + Err(message) => { + eprintln!("fastled: {message}"); + return test_exit(TestOutcome::Failure); + } + }; + let sketch_dir = PathBuf::from(dir); + if !sketch_dir.is_dir() { + eprintln!("fastled: sketch directory does not exist: {dir}"); + return test_exit(TestOutcome::Failure); + } + + announce_link_mode(cli, None, true); + + let output_dir = sketch_dir.join("fastled_js"); + if let Err(error) = std::fs::create_dir_all(&output_dir) { + eprintln!( + "fastled: could not create output directory {}: {error}", + output_dir.display() + ); + return test_exit(TestOutcome::Failure); + } + + let mut log_file = match open_test_log(plan.log_path.as_deref()) { + Ok(file) => file, + Err(error) => { + eprintln!("fastled: {error}"); + return test_exit(TestOutcome::Failure); + } + }; + let (build_tx, _build_rx) = tokio::sync::broadcast::channel::(256); + let (test_tx, mut test_rx) = tokio::sync::mpsc::unbounded_channel(); + let mut token_bytes = [0_u8; 32]; + if let Err(error) = getrandom::fill(&mut token_bytes) { + eprintln!("fastled: could not create test capability: {error}"); + return test_exit(TestOutcome::Failure); + } + let test_token = token_bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::(); + let debug_symbols: server::DebugSymbolHandle = Arc::new(RwLock::new(None)); + let screenshot_paths = plan + .screenshots + .iter() + .map(|(name, path)| (name.clone(), path.clone().into_path_buf())) + .collect::>(); + let runtime_config = server::TestRuntimeConfig { + wait_ms: plan.wait.as_secs_f64() * 1_000.0, + interval_ms: plan.interval.map(|value| value.as_secs_f64() * 1_000.0), + screenshot_names: plan + .screenshots + .iter() + .map(|(name, _)| name.clone()) + .collect(), + }; + + write_build_status(&output_dir, "compiling", "Compiling..."); + let rt = match tokio::runtime::Runtime::new() { + Ok(runtime) => runtime, + Err(error) => { + eprintln!("fastled: could not create test runtime: {error}"); + return test_exit(TestOutcome::Failure); + } + }; + rt.block_on(async { + let addr = match server::start_server( + output_dir.clone(), + 0, + Some(build_tx.clone()), + debug_symbols.clone(), + Some(server::TestServerOptions { + runtime: runtime_config, + screenshot_paths, + events: test_tx, + token: test_token.clone(), + sleep_permits: Arc::new(tokio::sync::Semaphore::new(4)), + }), + ) + .await + { + Ok(addr) => addr, + Err(error) => { + eprintln!("fastled: failed to start test server: {error}"); + return test_exit(TestOutcome::Failure); + } + }; + + send_sse( + &build_tx, + r#"{"type":"status","status":"compiling","message":"Compiling..."}"#, + ); + announce_link_mode(cli, Some(&build_tx), false); + let Some(compile_budget) = plan.total_timeout.checked_sub(started.elapsed()) else { + eprintln!("fastled: production test timed out before compilation"); + return test_exit(TestOutcome::TotalTimeout); + }; + let mut compile = match test_compile_command(cli, &sketch_dir) { + Ok(command) => command, + Err(error) => { + eprintln!("fastled: could not launch test compilation: {error}"); + return test_exit(TestOutcome::Failure); + } + }; + let compile_result = match test_mode::run_contained_command(&mut compile, compile_budget).await + { + Ok(result) => result, + Err(error) => { + eprintln!("fastled: test compilation process failed: {error}"); + return test_exit(TestOutcome::Failure); + } + }; + let success = matches!(compile_result, test_mode::TimedCommandResult::Exited(0)); + let effective_success = report_build_outcome(&output_dir, &build_tx, success, true); + if matches!(compile_result, test_mode::TimedCommandResult::Interrupted) { + eprintln!("fastled: production test interrupted during compilation"); + return test_exit(TestOutcome::Interrupted); + } + if matches!(compile_result, test_mode::TimedCommandResult::TimedOut) { + eprintln!("fastled: production test exceeded --test-timeout-secs during compilation"); + return test_exit(TestOutcome::TotalTimeout); + } + if !effective_success { + eprintln!("fastled: test compilation failed"); + return test_exit(TestOutcome::Failure); + } + + let url = format!("http://{addr}/#fastled-test-token={test_token}"); + let mut viewer = match viewer::launch_tauri_test_viewer(&url) { + Ok(process) => process, + Err(error) => { + eprintln!("fastled: Tauri test viewer failed: {error:#}"); + return test_exit(TestOutcome::Failure); + } + }; + + let Some(remaining) = plan.total_timeout.checked_sub(started.elapsed()) else { + eprintln!("fastled: production test timed out while launching the viewer"); + return test_exit(TestOutcome::TotalTimeout); + }; + let deadline_origin = tokio::time::Instant::now(); + let total_deadline = deadline_origin + remaining; + let ready_deadline = deadline_origin + plan.ready_timeout; + let ctrl_c = tokio::signal::ctrl_c(); + tokio::pin!(ctrl_c); + let mut liveness = tokio::time::interval(std::time::Duration::from_millis(100)); + let mut ready = false; + let mut page_error = false; + let mut saved = HashSet::new(); + + loop { + tokio::select! { + biased; + _ = tokio::time::sleep_until(total_deadline) => { + eprintln!("fastled: production test exceeded --test-timeout-secs"); + return test_exit(TestOutcome::TotalTimeout); + } + _ = tokio::time::sleep_until(ready_deadline), if !ready => { + eprintln!("fastled: viewer did not render a canvas before --test-ready-timeout-secs"); + return test_exit(TestOutcome::ReadyTimeout); + } + _ = &mut ctrl_c => { + eprintln!("fastled: production test interrupted"); + return test_exit(TestOutcome::Interrupted); + } + _ = liveness.tick() => { + if !viewer.is_alive() { + eprintln!("fastled: test viewer exited before completing"); + return test_exit(TestOutcome::Failure); + } + } + event = test_rx.recv() => { + match event { + Some(server::TestEvent::Ready) => { + if !ready { + ready = true; + if !write_test_log(&mut log_file, "[fastled-test] ready") { + return test_exit(TestOutcome::Failure); + } + } + } + Some(server::TestEvent::ViewerLog(line)) => { + page_error |= test_mode::is_viewer_error_line(&line); + if !write_test_log(&mut log_file, &line) { + return test_exit(TestOutcome::Failure); + } + } + Some(server::TestEvent::ScreenshotSaved { name, path }) => { + saved.insert(name); + let marker = format!("[fastled-test] screenshot={}", path.display()); + if !write_test_log(&mut log_file, &marker) { + return test_exit(TestOutcome::Failure); + } + } + Some(server::TestEvent::Failure(message)) => { + eprintln!("fastled: {message}"); + return test_exit(TestOutcome::Failure); + } + Some(server::TestEvent::Done(code)) => { + if !ready || code != 0 || saved.len() != plan.screenshots.len() { + eprintln!( + "fastled: viewer test failed (ready={ready}, code {code}, saved {}/{})", + saved.len(), + plan.screenshots.len() + ); + return test_exit(TestOutcome::Failure); + } + return test_exit(if plan.exit_on_error && page_error { + TestOutcome::PageError + } else { + TestOutcome::Success + }); + } + None => { + eprintln!("fastled: test event channel closed unexpectedly"); + return test_exit(TestOutcome::Failure); + } + } + } + } + } + }) +} + +fn test_exit(outcome: TestOutcome) -> ExitCode { + ExitCode::from(outcome.exit_code()) +} + +fn test_compile_command( + cli: &Cli, + sketch_dir: &std::path::Path, +) -> std::io::Result { + let mut command = std::process::Command::new(std::env::current_exe()?); + command + .arg(sketch_dir) + .arg("--just-compile") + .arg("--no-interactive"); + if cli.debug { + command.arg("--debug"); + } else if cli.release { + command.arg("--release"); + } else { + command.arg("--quick"); + } + command.arg(match cli.link_mode { + LinkMode::Static => "--link=static", + LinkMode::Dynamic => "--link=dynamic", + }); + if cli.profile { + command.arg("--profile"); + } + if cli.purge { + command.arg("--purge"); + } + if cli.clangd { + command.arg("--clangd"); + } + if let Some(path) = &cli.fastled_path { + command.arg("--fastled-path").arg(path); + } + Ok(command) +} + +fn open_test_log(path: Option<&std::path::Path>) -> Result, String> { + let Some(path) = path else { + return Ok(None); + }; + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + std::fs::create_dir_all(parent) + .map_err(|error| format!("could not create test log directory: {error}"))?; + } + OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map(Some) + .map_err(|error| format!("could not open test log {}: {error}", path.display())) +} + +fn write_test_log(file: &mut Option, line: &str) -> bool { + let Some(file) = file else { + return true; + }; + let timestamp = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis(); + if let Err(error) = writeln!(file, "[{timestamp}] {line}").and_then(|_| file.flush()) { + eprintln!("fastled: could not write test log: {error}"); + return false; + } + true +} + pub(crate) fn run_native_init(cli: &Cli, example: Option<&str>) -> ExitCode { if let Err(message) = validate_init_ref_flags(cli) { eprintln!("fastled: {message}"); @@ -395,7 +703,7 @@ pub(crate) fn serve_directory(dir: &str, launch_viewer: bool) -> ExitCode { let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); rt.block_on(async { let debug_symbols: server::DebugSymbolHandle = Arc::new(RwLock::new(resolver)); - let addr = match server::start_server(path.clone(), 0, None, debug_symbols).await { + let addr = match server::start_server(path.clone(), 0, None, debug_symbols, None).await { Ok(a) => a, Err(e) => { eprintln!("fastled: failed to start server: {e}"); diff --git a/crates/fastled-cli/src/dwarf_smoke.rs b/crates/fastled-cli/src/dwarf_smoke.rs index b814c812..5405f1c7 100644 --- a/crates/fastled-cli/src/dwarf_smoke.rs +++ b/crates/fastled-cli/src/dwarf_smoke.rs @@ -29,7 +29,7 @@ pub(crate) fn run_dwarf_source_smoke(output_dir: &Path) -> anyhow::Result let output_dir = output_dir.to_path_buf(); let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); rt.block_on(async move { - let addr = server::start_server(output_dir, 0, None, debug_symbols).await?; + let addr = server::start_server(output_dir, 0, None, debug_symbols, None).await?; tokio::time::sleep(std::time::Duration::from_millis(50)).await; let client = reqwest::Client::new(); for path in &paths { diff --git a/crates/fastled-cli/src/lib.rs b/crates/fastled-cli/src/lib.rs index c26f1cc2..cdb14821 100644 --- a/crates/fastled-cli/src/lib.rs +++ b/crates/fastled-cli/src/lib.rs @@ -25,6 +25,7 @@ pub mod project; pub mod runtime; mod selection; mod server; +mod test_mode; pub mod viewer; pub mod wasm_build; mod watcher; @@ -38,6 +39,7 @@ const DEFAULT_EXAMPLE: &str = "wasm"; /// Library entry point invoked by the `fastled` binary. pub fn run() -> ExitCode { let mut cli = cli::Cli::parse(); + cli::apply_test_implications(&mut cli); if let Err(message) = cli::validate_init_ref_flags(&cli) { eprintln!("fastled: {message}"); @@ -147,6 +149,9 @@ pub fn run() -> ExitCode { // - the user did NOT pass --just-compile // - it's not a non-compile command (--init) if let Some(ref dir) = cli.directory { + if cli.test && cli.init.is_none() { + return commands::compile_and_test(dir, &cli); + } if (cli.just_compile || cli.no_app) && cli.init.is_none() { return commands::run_native_just_compile(&cli, dir); } @@ -219,6 +224,16 @@ mod tests { dry_run: false, no_interactive: false, no_https: false, + test: false, + test_wait_secs: 1.0, + test_screenshot: None, + test_interval_secs: None, + test_count: None, + test_duration_secs: None, + test_log: None, + test_exit_on_error: false, + test_timeout_secs: 120.0, + test_ready_timeout_secs: 15.0, latest: false, branch: None, commit: None, diff --git a/crates/fastled-cli/src/main.rs b/crates/fastled-cli/src/main.rs index 67346816..2fca8b70 100644 --- a/crates/fastled-cli/src/main.rs +++ b/crates/fastled-cli/src/main.rs @@ -8,6 +8,7 @@ struct InternalViewerArgs { title: String, width: u32, height: u32, + inject_test_runtime: bool, } fn parse_internal_viewer_args() -> Option> { @@ -26,6 +27,7 @@ fn parse_internal_viewer_args() -> Option> { title: "FastLED Viewer".to_string(), width: 800, height: 600, + inject_test_runtime: false, }; while let Some(arg) = args.next() { @@ -52,6 +54,8 @@ fn parse_internal_viewer_args() -> Option> { Ok(height) => height, Err(_) => return Some(Err("--viewer-height must be an integer".to_string())), }; + } else if arg == "--viewer-inject-test-runtime" { + parsed.inject_test_runtime = true; } else { return Some(Err(format!( "unknown internal viewer argument: {}", @@ -79,6 +83,7 @@ fn run_internal_viewer(args: InternalViewerArgs) -> ExitCode { title: args.title, width: args.width, height: args.height, + inject_test_runtime: args.inject_test_runtime, }) } diff --git a/crates/fastled-cli/src/server.rs b/crates/fastled-cli/src/server.rs index c73c8c53..c87c77cb 100644 --- a/crates/fastled-cli/src/server.rs +++ b/crates/fastled-cli/src/server.rs @@ -5,18 +5,20 @@ //! does not exist yet (compilation in progress) a built-in loading page //! is returned that polls `/build-status.json` for live updates. +use std::collections::HashMap; use std::convert::Infallible; use std::net::SocketAddr; use std::path::PathBuf; use std::sync::{Arc, RwLock}; -use axum::extract::State; -use axum::http::{header, HeaderValue, Method, StatusCode}; +use axum::body::Bytes; +use axum::extract::{DefaultBodyLimit, Query, State}; +use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{Html, IntoResponse, Response}; use axum::routing::{get, post}; use axum::{Json, Router}; -use serde::Deserialize; +use serde::{Deserialize, Serialize}; use serde_json::json; use tokio::sync::broadcast; use tokio_stream::wrappers::BroadcastStream; @@ -34,6 +36,32 @@ use crate::debug_symbols::{DebugSymbolResolver, ResolveError}; /// the server. pub type DebugSymbolHandle = Arc>>; +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct TestRuntimeConfig { + pub(crate) wait_ms: f64, + pub(crate) interval_ms: Option, + pub(crate) screenshot_names: Vec, +} + +#[derive(Clone)] +pub(crate) struct TestServerOptions { + pub(crate) runtime: TestRuntimeConfig, + pub(crate) screenshot_paths: HashMap, + pub(crate) events: tokio::sync::mpsc::UnboundedSender, + pub(crate) token: String, + pub(crate) sleep_permits: Arc, +} + +#[derive(Debug)] +pub(crate) enum TestEvent { + Ready, + ViewerLog(String), + ScreenshotSaved { name: String, path: PathBuf }, + Failure(String), + Done(u8), +} + // --------------------------------------------------------------------------- // Loading page (shown while compilation is in progress) // --------------------------------------------------------------------------- @@ -188,6 +216,142 @@ const LOADING_PAGE: &str = r#"
"#; +const TEST_WORKER_WEBGL_PREFIX: &str = r#" +const __fastledOriginalOffscreenGetContext = OffscreenCanvas.prototype.getContext; +let __fastledTestWebglReported = false; +const __fastledTestContexts = []; + +const __fastledTestCaptureFrame = async (request) => { + const id = request.id; + try { + if (__fastledTestContexts.length === 0) throw new Error('FastLED WebGL context is unavailable'); + let selected = null; + const manager = typeof workerState !== 'undefined' && workerState.graphicsManager; + if (manager) { + const freshFrameData = extractFrameData(); + let nonzeroFrameValues = 0; + if (freshFrameData) { + for (const strip of freshFrameData) { + for (const value of strip.pixel_data || []) if (value > 0) nonzeroFrameValues += 1; + } + if (Object.keys(manager.screenMaps || {}).length === 0 && workerState.wasmFunctions) { + const Module = workerState.fastledModule; + const screenMapSizePtr = Module._malloc(4); + const screenMapDataPtr = workerState.wasmFunctions.getScreenMapData(screenMapSizePtr); + if (screenMapDataPtr) { + const screenMapSize = Module.getValue(screenMapSizePtr, 'i32'); + const screenMaps = JSON.parse(Module.UTF8ToString(screenMapDataPtr, screenMapSize)); + manager.updateScreenMap(screenMaps); + workerState.screenMaps = screenMaps; + workerState.wasmFunctions.freeFrameData(screenMapDataPtr); + } + Module._free(screenMapSizePtr); + } + manager.updateCanvas(freshFrameData); + } + postMessage({ + type: 'stdout', + payload: { text: `[fastled-test] synchronous frame values=${nonzeroFrameValues} screenMaps=${Object.keys(manager.screenMaps || {}).length}` } + }); + } + for (const entry of __fastledTestContexts) { + const width = entry.canvas.width; + const height = entry.canvas.height; + const pixels = new Uint8Array(width * height * 4); + const previousFramebuffer = entry.gl.getParameter(entry.gl.FRAMEBUFFER_BINDING); + let readError; + try { + entry.gl.bindFramebuffer(entry.gl.FRAMEBUFFER, null); + entry.gl.finish(); + entry.gl.readPixels(0, 0, width, height, entry.gl.RGBA, entry.gl.UNSIGNED_BYTE, pixels); + readError = entry.gl.getError(); + } finally { + entry.gl.bindFramebuffer(entry.gl.FRAMEBUFFER, previousFramebuffer); + } + if (readError !== entry.gl.NO_ERROR) { + throw new Error(`WebGL readPixels failed with error 0x${readError.toString(16)}`); + } + let nonBlackPixels = 0; + let varied = false; + const first = pixels.slice(0, 4); + for (let offset = 0; offset < pixels.length; offset += 4) { + if (pixels[offset] || pixels[offset + 1] || pixels[offset + 2]) nonBlackPixels += 1; + if (pixels[offset] !== first[0] || pixels[offset + 1] !== first[1] + || pixels[offset + 2] !== first[2] || pixels[offset + 3] !== first[3]) varied = true; + } + postMessage({ + type: 'stdout', + payload: { text: `[fastled-test] context ${entry.kind} ${width}x${height} nonBlack=${nonBlackPixels} varied=${varied}` } + }); + const candidate = { canvas: entry.canvas, gl: entry.gl, width, height, pixels, nonBlackPixels, varied }; + if (!selected || candidate.nonBlackPixels > selected.nonBlackPixels + || (candidate.nonBlackPixels === selected.nonBlackPixels && candidate.varied && !selected.varied) + || (candidate.nonBlackPixels === selected.nonBlackPixels && candidate.varied === selected.varied + && candidate.width * candidate.height > selected.width * selected.height)) { + selected = candidate; + } + } + const { width, height, pixels, nonBlackPixels, varied } = selected; + const flipped = new Uint8ClampedArray(pixels.length); + const rowBytes = width * 4; + for (let y = 0; y < height; y += 1) { + const source = (height - y - 1) * rowBytes; + flipped.set(pixels.subarray(source, source + rowBytes), y * rowBytes); + } + const output = new OffscreenCanvas(width, height); + const context = output.getContext('2d'); + if (!context) throw new Error('2D screenshot context is unavailable'); + context.putImageData(new ImageData(flipped, width, height), 0, 0); + const blob = await output.convertToBlob({ type: 'image/png' }); + const bytes = await blob.arrayBuffer(); + postMessage({ + type: 'fastled_test_capture_response', + id, + bytes, + stats: { width, height, nonBlackPixels, varied } + }, [bytes]); + } catch (error) { + postMessage({ + type: 'fastled_test_capture_response', + id, + error: error && error.stack ? error.stack : String(error) + }); + } +}; + +OffscreenCanvas.prototype.getContext = function(kind, attributes) { + if (kind === 'webgl' || kind === 'webgl2' || kind === 'experimental-webgl') { + attributes = Object.assign({}, attributes || {}, { preserveDrawingBuffer: true }); + if (!__fastledTestWebglReported) { + __fastledTestWebglReported = true; + postMessage({ + type: 'stdout', + payload: { text: '[fastled-test] OffscreenCanvas preserveDrawingBuffer enabled' } + }); + } + } + const context = __fastledOriginalOffscreenGetContext.call(this, kind, attributes); + if (context && (kind === 'webgl' || kind === 'webgl2' || kind === 'experimental-webgl')) { + __fastledTestContexts.push({ gl: context, canvas: this, kind }); + const effectiveAttributes = context.getContextAttributes(); + postMessage({ + type: 'stdout', + payload: { text: `[fastled-test] WebGL context ${kind} canvas=${this.width}x${this.height} preserveDrawingBuffer=${effectiveAttributes && effectiveAttributes.preserveDrawingBuffer}` } + }); + } + return context; +}; +self.addEventListener('message', (event) => { + if (!event.data || event.data.type !== 'fastled_test_capture') return; + event.stopImmediatePropagation(); + void __fastledTestCaptureFrame({ id: event.data.id }); + postMessage({ + type: 'stdout', + payload: { text: '[fastled-test] capture requested' } + }); +}); +"#; + // --------------------------------------------------------------------------- // Server state // --------------------------------------------------------------------------- @@ -201,6 +365,7 @@ struct AppState { /// Shared resolver for DWARF source paths. Empty until a successful /// build populates it. debug_symbols: DebugSymbolHandle, + test: Option>, } // --------------------------------------------------------------------------- @@ -250,7 +415,12 @@ async fn serve_file( } match tokio::fs::read(&file_path).await { - Ok(data) => { + Ok(mut data) => { + if state.test.is_some() && path == "fastled_background_worker.js" { + let mut patched = TEST_WORKER_WEBGL_PREFIX.as_bytes().to_vec(); + patched.extend_from_slice(&data); + data = patched; + } let mime = mime_for_path(&path); (StatusCode::OK, [(header::CONTENT_TYPE, mime)], data).into_response() } @@ -301,10 +471,140 @@ async fn build_stream(State(state): State) -> Response { /// `POST /viewer-log` — receive console/error lines forwarded from the Tauri /// viewer's injected logging script (enabled via `FASTLED_VIEWER_LOGS`) and /// echo them to stderr so viewer-side failures are diagnosable. -async fn viewer_log(body: String) -> Response { +fn test_request_authorized(test: &TestServerOptions, headers: &HeaderMap) -> bool { + headers + .get(header::AUTHORIZATION) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.strip_prefix("Bearer ")) + .is_some_and(|value| value == test.token) +} + +async fn viewer_log(State(state): State, headers: HeaderMap, body: String) -> Response { + if let Some(test) = &state.test { + if !test_request_authorized(test, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + } for line in body.lines() { eprintln!("[viewer] {line}"); + if let Some(test) = &state.test { + let _ = test.events.send(TestEvent::ViewerLog(line.to_string())); + } + } + StatusCode::NO_CONTENT.into_response() +} + +async fn test_config(State(state): State, headers: HeaderMap) -> Response { + match &state.test { + Some(test) if test_request_authorized(test, &headers) => { + Json(test.runtime.clone()).into_response() + } + Some(_) => StatusCode::UNAUTHORIZED.into_response(), + None => StatusCode::NOT_FOUND.into_response(), + } +} + +async fn test_ready(State(state): State, headers: HeaderMap) -> Response { + match &state.test { + Some(test) if test_request_authorized(test, &headers) => { + let _ = test.events.send(TestEvent::Ready); + StatusCode::NO_CONTENT.into_response() + } + Some(_) => StatusCode::UNAUTHORIZED.into_response(), + None => StatusCode::NOT_FOUND.into_response(), + } +} + +#[derive(Deserialize)] +struct TestSleepQuery { + ms: f64, +} + +async fn test_sleep( + State(state): State, + headers: HeaderMap, + Query(query): Query, +) -> Response { + let Some(test) = &state.test else { + return StatusCode::NOT_FOUND.into_response(); + }; + if !test_request_authorized(test, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Ok(duration) = std::time::Duration::try_from_secs_f64(query.ms / 1_000.0) else { + return (StatusCode::BAD_REQUEST, "invalid sleep duration").into_response(); + }; + let max_ms = test + .runtime + .interval_ms + .unwrap_or(0.0) + .max(test.runtime.wait_ms); + if query.ms > max_ms { + return (StatusCode::BAD_REQUEST, "sleep exceeds test schedule").into_response(); + } + let Ok(_permit) = test.sleep_permits.clone().try_acquire_owned() else { + return StatusCode::TOO_MANY_REQUESTS.into_response(); + }; + tokio::time::sleep(duration).await; + StatusCode::NO_CONTENT.into_response() +} + +#[derive(Deserialize)] +struct ScreenshotQuery { + name: String, +} + +async fn viewer_screenshot( + State(state): State, + headers: HeaderMap, + Query(query): Query, + body: Bytes, +) -> Response { + let Some(test) = &state.test else { + return StatusCode::NOT_FOUND.into_response(); + }; + if !test_request_authorized(test, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let Some(path) = test.screenshot_paths.get(&query.name) else { + return (StatusCode::BAD_REQUEST, "unknown screenshot name").into_response(); + }; + if body.len() < 8 || body[..8] != [137, 80, 78, 71, 13, 10, 26, 10] { + let message = format!("viewer returned invalid PNG data for {}", path.display()); + let _ = test.events.send(TestEvent::Failure(message.clone())); + return (StatusCode::BAD_REQUEST, message).into_response(); + } + if let Some(parent) = path + .parent() + .filter(|parent| !parent.as_os_str().is_empty()) + { + if let Err(error) = tokio::fs::create_dir_all(parent).await { + let message = format!("could not create screenshot directory: {error}"); + let _ = test.events.send(TestEvent::Failure(message.clone())); + return (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(); + } + } + if let Err(error) = tokio::fs::write(path, &body).await { + let message = format!("could not write screenshot {}: {error}", path.display()); + let _ = test.events.send(TestEvent::Failure(message.clone())); + return (StatusCode::INTERNAL_SERVER_ERROR, message).into_response(); } + let _ = test.events.send(TestEvent::ScreenshotSaved { + name: query.name, + path: path.clone(), + }); + StatusCode::NO_CONTENT.into_response() +} + +async fn test_done(State(state): State, headers: HeaderMap, body: String) -> Response { + let Some(test) = &state.test else { + return StatusCode::NOT_FOUND.into_response(); + }; + if !test_request_authorized(test, &headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + let code = body.trim().parse::().unwrap_or(1); + let _ = test.events.send(TestEvent::Done(code)); StatusCode::NO_CONTENT.into_response() } @@ -422,11 +722,13 @@ pub async fn start_server( port: u16, build_tx: Option>, debug_symbols: DebugSymbolHandle, + test: Option, ) -> anyhow::Result { let state = AppState { serve_dir: Arc::new(serve_dir), build_tx, debug_symbols, + test: test.map(Arc::new), }; let app = Router::new() @@ -434,6 +736,11 @@ pub async fn start_server( .route("/build-stream", get(build_stream)) .route("/dwarfsource", post(dwarf_source)) .route("/viewer-log", post(viewer_log)) + .route("/test-config", get(test_config)) + .route("/test-ready", post(test_ready)) + .route("/test-sleep", post(test_sleep)) + .route("/viewer-screenshot", post(viewer_screenshot)) + .route("/test-done", post(test_done)) .route("/debug/source-roots", get(debug_source_roots)) .route("/{*path}", get(serve_file)) .layer(SetResponseHeaderLayer::overriding( @@ -460,6 +767,7 @@ pub async fn start_server( ]) .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION]), ) + .layer(DefaultBodyLimit::max(64 * 1024 * 1024)) .with_state(state); let listener = tokio::net::TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port))).await?; @@ -488,7 +796,7 @@ mod tests { /// Helper: create a temp dir, start the server, return (addr, dir). async fn setup_server() -> (SocketAddr, tempfile::TempDir) { let dir = tempfile::tempdir().unwrap(); - let addr = start_server(dir.path().to_path_buf(), 0, None, empty_handle()) + let addr = start_server(dir.path().to_path_buf(), 0, None, empty_handle(), None) .await .unwrap(); // Give the server a moment to bind. @@ -509,6 +817,117 @@ mod tests { assert_eq!(resp.status(), 204); } + #[tokio::test] + async fn test_runtime_endpoints_use_preconfigured_screenshot_paths() { + let dir = tempfile::tempdir().unwrap(); + fs::write( + dir.path().join("fastled_background_worker.js"), + "console.log('worker');", + ) + .unwrap(); + let screenshot = dir.path().join("artifacts").join("frame.png"); + let (events, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let options = TestServerOptions { + runtime: TestRuntimeConfig { + wait_ms: 25.0, + interval_ms: Some(10.0), + screenshot_names: vec!["frame-0".to_string()], + }, + screenshot_paths: HashMap::from([("frame-0".to_string(), screenshot.clone())]), + events, + token: "test-token".to_string(), + sleep_permits: Arc::new(tokio::sync::Semaphore::new(4)), + }; + let addr = start_server( + dir.path().to_path_buf(), + 0, + None, + empty_handle(), + Some(options), + ) + .await + .unwrap(); + let client = reqwest::Client::new(); + + let unauthorized = client + .get(format!("http://{addr}/test-config")) + .send() + .await + .unwrap(); + assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED); + let config_response = client + .get(format!("http://{addr}/test-config")) + .bearer_auth("test-token") + .send() + .await + .unwrap(); + let config: serde_json::Value = + serde_json::from_str(&config_response.text().await.unwrap()).unwrap(); + assert_eq!(config["waitMs"].as_f64(), Some(25.0)); + assert_eq!(config["screenshotNames"][0], "frame-0"); + + let response = client + .post(format!("http://{addr}/test-sleep?ms=1")) + .bearer_auth("test-token") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + let response = client + .post(format!("http://{addr}/test-sleep?ms=-1")) + .bearer_auth("test-token") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + let response = client + .post(format!("http://{addr}/test-sleep?ms=26")) + .bearer_auth("test-token") + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + + let worker = client + .get(format!("http://{addr}/fastled_background_worker.js")) + .send() + .await + .unwrap() + .text() + .await + .unwrap(); + assert!(worker.starts_with("\nconst __fastledOriginalOffscreenGetContext")); + assert!(worker.contains("preserveDrawingBuffer: true")); + assert!(worker.contains("console.log('worker');")); + assert!(worker.contains("gl.readPixels")); + assert!(worker.contains("fastled_test_capture_response")); + + let response = client + .post(format!("http://{addr}/viewer-screenshot?name=..%2Fescape")) + .bearer_auth("test-token") + .body(vec![137, 80, 78, 71, 13, 10, 26, 10]) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert!(!dir.path().join("escape").exists()); + + let png = vec![137, 80, 78, 71, 13, 10, 26, 10, 1, 2, 3]; + let response = client + .post(format!("http://{addr}/viewer-screenshot?name=frame-0")) + .bearer_auth("test-token") + .body(png.clone()) + .send() + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::NO_CONTENT); + assert_eq!(fs::read(&screenshot).unwrap(), png); + assert!(matches!( + rx.recv().await, + Some(TestEvent::ScreenshotSaved { name, .. }) if name == "frame-0" + )); + } + #[tokio::test] async fn test_loading_page_when_no_index_html() { let (addr, _dir) = setup_server().await; @@ -684,6 +1103,7 @@ mod tests { 0, Some(tx.clone()), empty_handle(), + None, ) .await .unwrap(); @@ -836,7 +1256,7 @@ mod tests { let resolver = DebugSymbolResolver::new(load_debug_symbol_config(sketch_dir, None, None)); let handle: DebugSymbolHandle = Arc::new(RwLock::new(Some(resolver))); - let addr = start_server(dir.path().to_path_buf(), 0, None, handle.clone()) + let addr = start_server(dir.path().to_path_buf(), 0, None, handle.clone(), None) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(50)).await; @@ -876,7 +1296,9 @@ mod tests { let resolver = DebugSymbolResolver::new(load_debug_symbol_config(sketch_dir, None, None)); let handle: DebugSymbolHandle = Arc::new(RwLock::new(Some(resolver))); - let addr = start_server(serve_dir, 0, None, handle).await.unwrap(); + let addr = start_server(serve_dir, 0, None, handle, None) + .await + .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(50)).await; let resp = reqwest::get(format!("http://{addr}/sketchsource/src/demo.ino")) @@ -923,7 +1345,9 @@ mod tests { let handle: DebugSymbolHandle = Arc::new(RwLock::new(Some(DebugSymbolResolver::new(loaded)))); - let addr = start_server(serve_dir, 0, None, handle).await.unwrap(); + let addr = start_server(serve_dir, 0, None, handle, None) + .await + .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(50)).await; let resp = reqwest::get(format!("http://{addr}/sketchsource/src/demo.ino")) @@ -943,7 +1367,7 @@ mod tests { let resolver = DebugSymbolResolver::new(load_debug_symbol_config(sketch_dir, None, None)); let handle: DebugSymbolHandle = Arc::new(RwLock::new(Some(resolver))); - let addr = start_server(dir.path().to_path_buf(), 0, None, handle) + let addr = start_server(dir.path().to_path_buf(), 0, None, handle, None) .await .unwrap(); tokio::time::sleep(std::time::Duration::from_millis(50)).await; diff --git a/crates/fastled-cli/src/tauri_viewer.rs b/crates/fastled-cli/src/tauri_viewer.rs index 10b9b9df..34d442c7 100644 --- a/crates/fastled-cli/src/tauri_viewer.rs +++ b/crates/fastled-cli/src/tauri_viewer.rs @@ -5,15 +5,35 @@ pub struct ViewerOptions { pub title: String, pub width: u32, pub height: u32, + pub inject_test_runtime: bool, } +const TEST_CAPABILITY_SCRIPT: &str = r#" +(() => { + const params = new URLSearchParams(location.hash.slice(1)); + const token = params.get('fastled-test-token'); + if (token) { + window.__fastled_test_token = token; + history.replaceState(null, '', location.pathname + location.search); + } +})(); +"#; + /// Injected when `FASTLED_VIEWER_LOGS` is enabled: forwards `console.*`, /// uncaught errors, unhandled rejections, and failed fetches to the FastLED /// HTTP server's `POST /viewer-log` endpoint, which echoes them to stderr. const LOG_FORWARD_SCRIPT: &str = r#" (() => { + const pending = window.__fastled_test_pending_logs = new Set(); const send = (line) => { - try { fetch('/viewer-log', { method: 'POST', body: line }); } catch (_) {} + try { + const headers = window.__fastled_test_token + ? { 'Authorization': 'Bearer ' + window.__fastled_test_token } + : {}; + const request = fetch('/viewer-log', { method: 'POST', headers, body: line }).catch(() => {}); + pending.add(request); + request.finally(() => pending.delete(request)); + } catch (_) {} }; const fmt = (args) => Array.from(args).map((a) => { if (a instanceof Error) return a.stack || String(a); @@ -48,6 +68,255 @@ const LOG_FORWARD_SCRIPT: &str = r#" })(); "#; +/// Runs before page JavaScript. It forces WebGL drawing-buffer preservation, +/// waits for a real rendered canvas, then follows the host-provided schedule. +const TEST_RUNTIME_SCRIPT: &str = r#" +(() => { + const originalGetContext = HTMLCanvasElement.prototype.getContext; + HTMLCanvasElement.prototype.getContext = function(kind, attributes) { + if (kind === 'webgl' || kind === 'webgl2' || kind === 'experimental-webgl') { + attributes = Object.assign({}, attributes || {}, { preserveDrawingBuffer: true }); + } + return originalGetContext.call(this, kind, attributes); + }; + + window.__fastled_test = window.__fastled_test || { version: 1 }; + const testFetch = (url, options = {}) => fetch(url, { + ...options, + headers: { + ...(options.headers || {}), + 'Authorization': 'Bearer ' + window.__fastled_test_token + } + }); + const hostSleep = async (ms) => { + if (ms <= 0) return; + const response = await testFetch('/test-sleep?ms=' + encodeURIComponent(ms), { method: 'POST' }); + if (!response.ok) throw new Error('test sleep failed: ' + response.status); + }; + const postDone = async (code) => { + const pending = window.__fastled_test_pending_logs; + if (pending) await Promise.allSettled(Array.from(pending)); + let lastError = new Error('test completion request failed'); + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + const response = await testFetch('/test-done', { method: 'POST', body: String(code) }); + if (response.ok) return; + lastError = new Error('test completion request failed: ' + response.status); + } catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + } + } + window.close(); + throw lastError; + }; + const workerFrameDataUrl = async () => { + const manager = window.fastLEDWorkerManager; + if (!manager || !manager.worker) return null; + if (!manager.isWorkerActive) throw new Error('FastLED render worker is not ready'); + let bitmap = null; + let resolveFrame; + let rejectFrame; + const frame = new Promise((resolve, reject) => { + resolveFrame = resolve; + rejectFrame = reject; + }); + const timeout = setTimeout(() => rejectFrame(new Error('worker screenshot frame timed out')), 3000); + const onMessage = (event) => { + if (event.data && event.data.type === 'frame_update' && event.data.payload?.bitmap) { + resolveFrame(event.data.payload); + } + }; + manager.worker.addEventListener('message', onMessage); + try { + const response = await manager.sendMessageWithResponse({ + type: 'start_recording', + payload: { fps: 60, settings: {} } + }); + if (!response || !response.success) throw new Error('worker screenshot capture did not start'); + const payload = await frame; + bitmap = payload.bitmap; + const mirror = document.createElement('canvas'); + mirror.width = payload.width; + mirror.height = payload.height; + const context = mirror.getContext('2d'); + if (!context) throw new Error('2D screenshot context unavailable'); + context.drawImage(bitmap, 0, 0); + return mirror.toDataURL('image/png'); + } finally { + clearTimeout(timeout); + manager.worker.removeEventListener('message', onMessage); + if (bitmap && typeof bitmap.close === 'function') bitmap.close(); + try { + await manager.sendMessageWithResponse({ type: 'stop_recording', payload: {} }); + } catch (_) {} + } + }; + const compositedFrameDataUrl = async (canvas) => { + if (typeof canvas.captureStream !== 'function') return null; + const stream = canvas.captureStream(0); + const track = stream.getVideoTracks()[0]; + if (!track) return null; + let bitmap = null; + let video = null; + try { + if (typeof ImageCapture !== 'undefined') { + if (typeof track.requestFrame === 'function') track.requestFrame(); + bitmap = await new ImageCapture(track).grabFrame(); + } else { + video = document.createElement('video'); + video.muted = true; + video.playsInline = true; + video.style.cssText = 'position:fixed;width:1px;height:1px;opacity:0;pointer-events:none'; + video.srcObject = stream; + document.body.appendChild(video); + const frameReady = new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error('composited screenshot frame timed out')), 3000); + const done = () => { clearTimeout(timeout); resolve(); }; + if (typeof video.requestVideoFrameCallback === 'function') { + video.requestVideoFrameCallback(done); + } else { + video.addEventListener('loadeddata', done, { once: true }); + } + }); + await video.play(); + if (typeof track.requestFrame === 'function') track.requestFrame(); + await frameReady; + bitmap = video; + } + const mirror = document.createElement('canvas'); + mirror.width = bitmap.width || bitmap.videoWidth || canvas.width; + mirror.height = bitmap.height || bitmap.videoHeight || canvas.height; + const context = mirror.getContext('2d'); + if (!context) throw new Error('2D screenshot context unavailable'); + context.drawImage(bitmap, 0, 0); + return mirror.toDataURL('image/png'); + } finally { + if (bitmap && bitmap !== video && typeof bitmap.close === 'function') bitmap.close(); + if (video) video.remove(); + stream.getTracks().forEach((item) => item.stop()); + } + }; + const webglFrameBlob = async () => { + const manager = window.fastLEDWorkerManager; + if (!manager || !manager.worker || !manager.isWorkerActive) return null; + const id = 'capture-' + Date.now() + '-' + Math.random(); + let resolveCapture; + let rejectCapture; + const response = new Promise((resolve, reject) => { + resolveCapture = resolve; + rejectCapture = reject; + }); + const timeout = setTimeout(() => rejectCapture(new Error('WebGL screenshot timed out')), 3000); + const onMessage = (event) => { + if (event.data && event.data.type === 'fastled_test_capture_response' && event.data.id === id) { + resolveCapture(event.data); + } + }; + manager.worker.addEventListener('message', onMessage); + try { + manager.worker.postMessage({ type: 'fastled_test_capture', id }); + const result = await response; + if (result.error) throw new Error(result.error); + console.log('[fastled-test] capture pixels=' + result.stats.width + 'x' + result.stats.height + + ' nonBlack=' + result.stats.nonBlackPixels + ' varied=' + result.stats.varied); + return new Blob([result.bytes], { type: 'image/png' }); + } finally { + clearTimeout(timeout); + manager.worker.removeEventListener('message', onMessage); + } + }; + const capture = async (canvas, name) => { + let blob = await webglFrameBlob(); + if (!blob) { + const dataUrl = await compositedFrameDataUrl(canvas) + || await workerFrameDataUrl() + || canvas.toDataURL('image/png'); + blob = await (await fetch(dataUrl)).blob(); + } + const response = await testFetch('/viewer-screenshot?name=' + encodeURIComponent(name), { + method: 'POST', + headers: { 'Content-Type': 'application/octet-stream' }, + body: blob + }); + if (!response.ok) throw new Error('screenshot upload failed: ' + response.status); + }; + + let finding = false; + let frameSeen = false; + let frameListenerInstalled = false; + const findCanvas = () => { + if (finding) return; + finding = true; + const tryFind = () => { + const canvas = document.getElementById('myCanvas') || document.querySelector('canvas'); + const manager = window.fastLEDWorkerManager; + if (!frameListenerInstalled && window.fastLEDEvents) { + frameListenerInstalled = true; + window.fastLEDEvents.on('frame:rendered', () => { frameSeen = true; }); + } + if (!canvas || !manager || !manager.isWorkerActive || !frameSeen) { + setTimeout(tryFind, 50); + return; + } + requestAnimationFrame(() => requestAnimationFrame(async () => { + try { + const ready = await testFetch('/test-ready', { method: 'POST' }); + if (!ready.ok) throw new Error('ready signal failed: ' + ready.status); + const response = await testFetch('/test-config'); + if (!response.ok) throw new Error('test config failed: ' + response.status); + const config = await response.json(); + const firstCaptureAt = performance.now() + config.waitMs; + const maxInFlightCaptures = 2; + const inFlightCaptures = new Set(); + const captureResults = []; + let firstCaptureFailure = null; + let signalCaptureFailure; + const captureFailureSignal = new Promise((resolve) => { signalCaptureFailure = resolve; }); + for (let index = 0; index < config.screenshotNames.length; index += 1) { + const deadline = firstCaptureAt + index * config.intervalMs; + const scheduledWait = hostSleep(Math.max(0, deadline - performance.now())).then( + () => null, + (error) => error instanceof Error ? error : new Error(String(error)) + ); + const waitFailure = await Promise.race([scheduledWait, captureFailureSignal]); + if (waitFailure && !firstCaptureFailure) firstCaptureFailure = waitFailure; + if (firstCaptureFailure) break; + if (inFlightCaptures.size >= maxInFlightCaptures) { + await Promise.race(inFlightCaptures); + } + if (firstCaptureFailure) break; + const task = capture(canvas, config.screenshotNames[index]).then( + () => null, + (error) => { + const failure = error instanceof Error ? error : new Error(String(error)); + if (!firstCaptureFailure) { + firstCaptureFailure = failure; + signalCaptureFailure(failure); + } + return failure; + } + ); + inFlightCaptures.add(task); + captureResults.push(task); + void task.finally(() => inFlightCaptures.delete(task)); + } + const failures = (await Promise.all(captureResults)).filter(Boolean); + if (firstCaptureFailure) throw firstCaptureFailure; + if (failures.length > 0) throw failures[0]; + await postDone(0); + } catch (error) { + console.error('[fastled-test] ' + (error && error.stack ? error.stack : String(error))); + try { await postDone(1); } catch (_) {} + } + })); + }; + tryFind(); + }; + document.addEventListener('DOMContentLoaded', findCanvas, { once: true }); + if (document.readyState !== 'loading') findCanvas(); +})(); +"#; + fn env_flag_enabled(value: Option<&str>) -> bool { matches!(value, Some(v) if !v.is_empty() && v != "0") } @@ -63,6 +332,7 @@ pub fn run(options: ViewerOptions) -> ExitCode { title, width, height, + inject_test_runtime, } = options; let result = tauri::Builder::default() @@ -72,9 +342,15 @@ pub fn run(options: ViewerOptions) -> ExitCode { let mut builder = tauri::WebviewWindowBuilder::new(app, "main", url) .title(&title) .inner_size(width as f64, height as f64); - if viewer_logs_enabled() { + if inject_test_runtime { + builder = builder.initialization_script(TEST_CAPABILITY_SCRIPT); + } + if viewer_logs_enabled() || inject_test_runtime { builder = builder.initialization_script(LOG_FORWARD_SCRIPT); } + if inject_test_runtime { + builder = builder.initialization_script(TEST_RUNTIME_SCRIPT); + } let window = builder.build()?; // Counteract WebView2 DPI auto-scaling while keeping the UI readable. @@ -116,7 +392,32 @@ mod tests { #[test] fn log_forward_script_targets_server_endpoint() { assert!(LOG_FORWARD_SCRIPT.contains("/viewer-log")); + assert!(LOG_FORWARD_SCRIPT.contains("Bearer ' + window.__fastled_test_token")); assert!(LOG_FORWARD_SCRIPT.contains("unhandledrejection")); assert!(LOG_FORWARD_SCRIPT.contains("window.addEventListener('error'")); } + + #[test] + fn test_runtime_patches_webgl_before_capturing() { + assert!(TEST_RUNTIME_SCRIPT.contains("preserveDrawingBuffer: true")); + assert!(TEST_RUNTIME_SCRIPT.contains("type: 'start_recording'")); + assert!(TEST_RUNTIME_SCRIPT.contains("canvas.captureStream(0)")); + assert!(TEST_RUNTIME_SCRIPT.contains("new ImageCapture(track).grabFrame()")); + assert!(TEST_RUNTIME_SCRIPT.contains("type === 'frame_update'")); + assert!(TEST_RUNTIME_SCRIPT.contains("document.getElementById('myCanvas')")); + assert!(TEST_RUNTIME_SCRIPT.contains("manager.isWorkerActive")); + assert!(TEST_RUNTIME_SCRIPT.contains("frame:rendered")); + assert!(TEST_RUNTIME_SCRIPT.contains("requestAnimationFrame(() => requestAnimationFrame")); + assert!(TEST_RUNTIME_SCRIPT.contains("/test-ready")); + assert!(TEST_RUNTIME_SCRIPT.contains("/viewer-screenshot?name=")); + assert!(TEST_RUNTIME_SCRIPT.contains("firstCaptureAt + index * config.intervalMs")); + assert!(TEST_CAPABILITY_SCRIPT.contains("fastled-test-token")); + assert!(TEST_CAPABILITY_SCRIPT.contains("history.replaceState")); + assert!(TEST_RUNTIME_SCRIPT.contains("testFetch('/test-sleep?ms='")); + assert!(TEST_RUNTIME_SCRIPT.contains("'Authorization': 'Bearer '")); + assert!(TEST_RUNTIME_SCRIPT.contains("maxInFlightCaptures = 2")); + assert!(TEST_RUNTIME_SCRIPT.contains("Promise.race([scheduledWait, captureFailureSignal])")); + assert!(TEST_RUNTIME_SCRIPT.contains("await Promise.all(captureResults)")); + assert!(TEST_RUNTIME_SCRIPT.contains("/test-done")); + } } diff --git a/crates/fastled-cli/src/test_mode.rs b/crates/fastled-cli/src/test_mode.rs new file mode 100644 index 00000000..c9bcd2a9 --- /dev/null +++ b/crates/fastled-cli/src/test_mode.rs @@ -0,0 +1,385 @@ +use std::process::Command; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use crate::cli::Cli; +use crate::path::NormalizedPath; +#[cfg(test)] +use crate::server::TestEvent; + +const MAX_TEST_SCREENSHOTS: usize = 100_000; +const MAX_TEST_DURATION: Duration = Duration::from_millis(i32::MAX as u64); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TestOutcome { + Success, + Failure, + PageError, + TotalTimeout, + ReadyTimeout, + Interrupted, +} + +impl TestOutcome { + pub(crate) fn exit_code(self) -> u8 { + match self { + Self::Success => 0, + Self::Failure => 1, + Self::PageError => 2, + Self::TotalTimeout => 124, + Self::ReadyTimeout => 125, + Self::Interrupted => 130, + } + } +} + +#[derive(Debug)] +pub(crate) struct TestPlan { + pub(crate) wait: Duration, + pub(crate) interval: Option, + pub(crate) ready_timeout: Duration, + pub(crate) total_timeout: Duration, + pub(crate) screenshots: Vec<(String, NormalizedPath)>, + pub(crate) log_path: Option, + pub(crate) exit_on_error: bool, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(crate) enum TimedCommandResult { + Exited(i32), + TimedOut, + Interrupted, +} + +pub(crate) async fn run_contained_command( + command: &mut Command, + timeout: Duration, +) -> std::io::Result { + let group = running_process::ContainedProcessGroup::with_originator("FASTLED_TEST")?; + let mut child = group.spawn(command, running_process::SpawnStdio::default())?; + let deadline = tokio::time::Instant::now() + timeout; + let ctrl_c = tokio::signal::ctrl_c(); + tokio::pin!(ctrl_c); + loop { + if let Some(code) = child.try_wait()? { + return Ok(TimedCommandResult::Exited(code)); + } + if tokio::time::Instant::now() >= deadline { + drop(child); + return Ok(TimedCommandResult::TimedOut); + } + tokio::select! { + _ = &mut ctrl_c => { + drop(child); + return Ok(TimedCommandResult::Interrupted); + } + _ = tokio::time::sleep(Duration::from_millis(10)) => {} + } + } +} + +pub(crate) fn build_test_plan(cli: &Cli) -> Result { + let wait = duration_from_nonnegative("--test-wait-secs", cli.test_wait_secs)?; + let total_timeout = duration_from_positive("--test-timeout-secs", cli.test_timeout_secs)?; + let ready_timeout = + duration_from_positive("--test-ready-timeout-secs", cli.test_ready_timeout_secs)?; + + if (cli.test_count.is_some() || cli.test_duration_secs.is_some()) + && cli.test_interval_secs.is_none() + { + return Err( + "--test-count and --test-duration-secs require --test-interval-secs".to_string(), + ); + } + + let interval = match cli.test_interval_secs { + Some(seconds) => { + let duration = duration_from_positive("--test-interval-secs", seconds)?; + if cli.test_screenshot.is_none() { + return Err("--test-interval-secs requires --test-screenshot".to_string()); + } + if cli.test_count.is_none() && cli.test_duration_secs.is_none() { + return Err( + "--test-interval-secs requires --test-count or --test-duration-secs" + .to_string(), + ); + } + Some(duration) + } + None => None, + }; + + if matches!(cli.test_count, Some(0)) { + return Err("--test-count must be greater than zero".to_string()); + } + let capture_duration = cli + .test_duration_secs + .map(|seconds| duration_from_positive("--test-duration-secs", seconds)) + .transpose()?; + + let screenshot_count = if cli.test_screenshot.is_none() { + 0 + } else if let Some(count) = cli.test_count { + count as usize + } else if let (Some(duration), Some(interval)) = (capture_duration, interval) { + usize::try_from(duration.as_nanos().div_ceil(interval.as_nanos())) + .map_err(|_| "requested screenshot count is too large".to_string())? + } else { + 1 + }; + if screenshot_count > MAX_TEST_SCREENSHOTS { + return Err(format!( + "requested {screenshot_count} screenshots; maximum is {MAX_TEST_SCREENSHOTS}" + )); + } + + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() as u64; + let mut screenshots = Vec::with_capacity(screenshot_count); + if let Some(template) = cli.test_screenshot.as_deref() { + let template = template.to_string_lossy(); + if screenshot_count > 1 && !has_varying_placeholder(&template) { + return Err( + "interval screenshots require a {n}, {n:WIDTH}, or {ts} placeholder".to_string(), + ); + } + for index in 0..screenshot_count { + let timestamp_step = interval + .map(|value| (value.as_millis() as u64).max(1)) + .unwrap_or(0); + let timestamp = timestamp_step + .checked_mul(index as u64) + .and_then(|step| now_ms.checked_add(step)) + .ok_or_else(|| "screenshot timestamp overflow".to_string())?; + screenshots.push(( + index.to_string(), + expand_screenshot_template(&template, index, timestamp)?, + )); + } + } + + Ok(TestPlan { + wait, + interval, + ready_timeout, + total_timeout, + screenshots, + log_path: cli.test_log.as_deref().map(NormalizedPath::new), + exit_on_error: cli.test_exit_on_error, + }) +} + +fn duration_from_positive(flag: &str, value: f64) -> Result { + if !value.is_finite() || value <= 0.0 { + return Err(format!("{flag} must be a finite number greater than zero")); + } + checked_test_duration(flag, value) +} + +fn duration_from_nonnegative(flag: &str, value: f64) -> Result { + if !value.is_finite() || value < 0.0 { + return Err(format!("{flag} must be a finite non-negative number")); + } + checked_test_duration(flag, value) +} + +fn checked_test_duration(flag: &str, value: f64) -> Result { + let duration = + Duration::try_from_secs_f64(value).map_err(|_| format!("{flag} is too large"))?; + if duration > MAX_TEST_DURATION { + return Err(format!( + "{flag} exceeds the maximum supported timer duration" + )); + } + Ok(duration) +} + +fn has_varying_placeholder(template: &str) -> bool { + template.contains("{n}") || template.contains("{ts}") || template.contains("{n:") +} + +pub(crate) fn expand_screenshot_template( + template: &str, + index: usize, + timestamp_ms: u64, +) -> Result { + let mut output = String::with_capacity(template.len() + 16); + let mut rest = template; + while let Some(open) = rest.find('{') { + output.push_str(&rest[..open]); + let placeholder_text = &rest[open + 1..]; + let Some(close_offset) = placeholder_text.find('}') else { + return Err(format!("unclosed screenshot placeholder in '{template}'")); + }; + let placeholder = &placeholder_text[..close_offset]; + match placeholder { + "n" => output.push_str(&index.to_string()), + "ts" => output.push_str(×tamp_ms.to_string()), + value if value.starts_with("n:") => { + let spec = &value[2..]; + let width_text = spec.strip_prefix('0').unwrap_or(spec); + let width = width_text.parse::().map_err(|_| { + format!("invalid screenshot index placeholder '{{{placeholder}}}'") + })?; + output.push_str(&format!("{index:0width$}")); + } + _ => { + return Err(format!( + "unknown screenshot placeholder '{{{placeholder}}}'" + )) + } + } + rest = &placeholder_text[close_offset + 1..]; + } + output.push_str(rest); + Ok(NormalizedPath::new(output)) +} + +pub(crate) fn is_viewer_error_line(line: &str) -> bool { + let line = line.trim_start(); + line.starts_with("error:") + || line.starts_with("window.onerror:") + || line.starts_with("unhandledrejection:") + || line.starts_with("fetch failed:") + || line.starts_with("fetch error:") +} + +#[cfg(test)] +pub(crate) async fn wait_for_ready( + rx: &mut tokio::sync::mpsc::UnboundedReceiver, + timeout: Duration, +) -> TestOutcome { + match tokio::time::timeout(timeout, async { + while let Some(event) = rx.recv().await { + if matches!(event, TestEvent::Ready) { + return true; + } + } + false + }) + .await + { + Ok(true) => TestOutcome::Success, + Ok(false) => TestOutcome::Failure, + Err(_) => TestOutcome::ReadyTimeout, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[test] + fn filename_template_expands_padded_indices_and_timestamps() { + assert_eq!( + expand_screenshot_template("out-{n:03}-{ts}.png", 7, 1234).unwrap(), + NormalizedPath::new("out-007-1234.png") + ); + assert_eq!( + expand_screenshot_template("out-{n}.png", 12, 1234).unwrap(), + NormalizedPath::new("out-12.png") + ); + } + + #[test] + fn exit_code_mapping_is_stable() { + assert_eq!(TestOutcome::Success.exit_code(), 0); + assert_eq!(TestOutcome::Failure.exit_code(), 1); + assert_eq!(TestOutcome::PageError.exit_code(), 2); + assert_eq!(TestOutcome::TotalTimeout.exit_code(), 124); + assert_eq!(TestOutcome::ReadyTimeout.exit_code(), 125); + assert_eq!(TestOutcome::Interrupted.exit_code(), 130); + } + + #[test] + fn viewer_error_lines_are_classified_without_false_positives() { + for line in [ + "error: boom", + "window.onerror: boom", + "unhandledrejection: boom", + "fetch failed: 500 /bad", + "fetch error: /bad network", + ] { + assert!(is_viewer_error_line(line), "expected error: {line}"); + } + for line in ["log: hello", "info: ready", "warn: benign"] { + assert!(!is_viewer_error_line(line), "unexpected error: {line}"); + } + } + + #[tokio::test] + async fn waiting_for_ready_has_a_distinct_timeout() { + let (_tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let outcome = wait_for_ready(&mut rx, Duration::from_millis(1)).await; + assert_eq!(outcome, TestOutcome::ReadyTimeout); + } + + #[test] + fn duration_mode_uses_a_deterministic_ceiling_frame_count() { + let cli = Cli::parse_from([ + "fastled", + "sketch", + "--test", + "--test-interval-secs=0.3", + "--test-duration-secs=1.0", + "--test-screenshot=out-{n}.png", + ]); + assert_eq!(build_test_plan(&cli).unwrap().screenshots.len(), 4); + } + + #[test] + fn timestamp_only_templates_remain_unique_below_one_millisecond() { + let cli = Cli::parse_from([ + "fastled", + "sketch", + "--test", + "--test-interval-secs=0.0005", + "--test-count=3", + "--test-screenshot=out-{ts}.png", + ]); + let plan = build_test_plan(&cli).unwrap(); + assert_ne!(plan.screenshots[0].1, plan.screenshots[1].1); + assert_ne!(plan.screenshots[1].1, plan.screenshots[2].1); + } + + #[test] + fn extreme_durations_and_counts_are_rejected_without_panicking() { + let huge_duration = + Cli::parse_from(["fastled", "sketch", "--test", "--test-timeout-secs=1e300"]); + assert!(build_test_plan(&huge_duration).is_err()); + + let huge_count = Cli::parse_from([ + "fastled", + "sketch", + "--test", + "--test-interval-secs=1", + "--test-count=100001", + "--test-screenshot=out-{n}.png", + ]); + assert!(build_test_plan(&huge_count).is_err()); + } + + #[tokio::test] + async fn contained_command_is_stopped_at_the_hard_deadline() { + #[cfg(windows)] + let mut command = { + let mut command = Command::new("cmd"); + command.args(["/C", "ping -n 3 127.0.0.1 >NUL"]); + command + }; + #[cfg(not(windows))] + let mut command = { + let mut command = Command::new("sh"); + command.args(["-c", "sleep 2"]); + command + }; + let started = std::time::Instant::now(); + let result = run_contained_command(&mut command, Duration::from_millis(30)) + .await + .unwrap(); + assert_eq!(result, TimedCommandResult::TimedOut); + assert!(started.elapsed() < Duration::from_secs(1)); + } +} diff --git a/crates/fastled-cli/src/viewer.rs b/crates/fastled-cli/src/viewer.rs index 314924f7..546c5e05 100644 --- a/crates/fastled-cli/src/viewer.rs +++ b/crates/fastled-cli/src/viewer.rs @@ -189,11 +189,13 @@ impl Drop for ViewerProcess { } #[cfg(any(not(windows), test))] -fn viewer_command(binary: &Path, url: &str) -> Command { +fn viewer_command(binary: &Path, url: &str, inject_test_runtime: bool) -> Command { let mut command = Command::new(binary); + command.arg("--internal-viewer").arg(url); + if inject_test_runtime { + command.arg("--viewer-inject-test-runtime"); + } command - .arg("--internal-viewer") - .arg(url) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()); @@ -241,14 +243,17 @@ fn quote_windows_arg(arg: &std::ffi::OsStr) -> String { } #[cfg(windows)] -fn viewer_command_line(binary: &Path, url: &str) -> Vec { +fn viewer_command_line(binary: &Path, url: &str, inject_test_runtime: bool) -> Vec { use std::os::windows::ffi::OsStrExt; - let args = [ + let mut args = vec![ binary.as_os_str(), std::ffi::OsStr::new("--internal-viewer"), std::ffi::OsStr::new(url), ]; + if inject_test_runtime { + args.push(std::ffi::OsStr::new("--viewer-inject-test-runtime")); + } let command_line = args .iter() .map(|arg| quote_windows_arg(arg)) @@ -261,7 +266,11 @@ fn viewer_command_line(binary: &Path, url: &str) -> Vec { } #[cfg(windows)] -fn spawn_hidden_viewer(binary: &Path, url: &str) -> Result { +fn spawn_hidden_viewer( + binary: &Path, + url: &str, + inject_test_runtime: bool, +) -> Result { use std::mem::{size_of, zeroed}; use std::ptr::{null, null_mut}; @@ -305,7 +314,7 @@ fn spawn_hidden_viewer(binary: &Path, url: &str) -> Result { startup_info.wShowWindow = 0; // SW_HIDE let mut process_info: PROCESS_INFORMATION = unsafe { zeroed() }; - let mut command_line = viewer_command_line(binary, url); + let mut command_line = viewer_command_line(binary, url, inject_test_runtime); let flags = VIEWER_CREATION_FLAGS | CREATE_SUSPENDED; let create_ok = unsafe { CreateProcessW( @@ -379,6 +388,14 @@ fn spawn_hidden_viewer(binary: &Path, url: &str) -> Result { /// reloads on build completion); pointing it at a directory or `fastled://` /// path regresses to a dead "Not Found" page (issues #151/#160). pub fn launch_tauri_viewer(url: &str) -> Result { + launch_tauri_viewer_with_options(url, false) +} + +pub(crate) fn launch_tauri_test_viewer(url: &str) -> Result { + launch_tauri_viewer_with_options(url, true) +} + +fn launch_tauri_viewer_with_options(url: &str, inject_test_runtime: bool) -> Result { if !url.starts_with("http://") && !url.starts_with("https://") { anyhow::bail!( "viewer must be launched with an http(s) URL pointing at the FastLED server, got: {url}" @@ -390,14 +407,14 @@ pub fn launch_tauri_viewer(url: &str) -> Result { #[cfg(windows)] { - spawn_hidden_viewer(&binary, url) + spawn_hidden_viewer(&binary, url, inject_test_runtime) } #[cfg(not(windows))] { let group = ContainedProcessGroup::new().context("failed to create viewer process group")?; - let mut command = viewer_command(&binary, url); + let mut command = viewer_command(&binary, url, inject_test_runtime); let stdio = SpawnStdio { stdin: StdioSource::Null, stdout: StdioSource::Null, @@ -550,7 +567,11 @@ mod tests { #[test] fn test_viewer_command_uses_internal_viewer_flag() { - let command = viewer_command(Path::new(FASTLED_EXE_NAMES[0]), "http://127.0.0.1:8089"); + let command = viewer_command( + Path::new(FASTLED_EXE_NAMES[0]), + "http://127.0.0.1:8089", + false, + ); let args = command .get_args() .map(|arg| arg.to_string_lossy().into_owned()) @@ -558,6 +579,27 @@ mod tests { assert_eq!(args, vec!["--internal-viewer", "http://127.0.0.1:8089"]); } + #[test] + fn test_viewer_command_can_inject_test_runtime() { + let command = viewer_command( + Path::new(FASTLED_EXE_NAMES[0]), + "http://127.0.0.1:8089", + true, + ); + let args = command + .get_args() + .map(|arg| arg.to_string_lossy().into_owned()) + .collect::>(); + assert_eq!( + args, + vec![ + "--internal-viewer", + "http://127.0.0.1:8089", + "--viewer-inject-test-runtime" + ] + ); + } + #[test] fn test_launch_tauri_viewer_rejects_directory_path() { // Regression gate for #151/#160: the viewer must never be pointed at