diff --git a/.changepacks/changepack_log_qPizzaodAj-f1Uz8PVvqE.json b/.changepacks/changepack_log_qPizzaodAj-f1Uz8PVvqE.json new file mode 100644 index 00000000..09110574 --- /dev/null +++ b/.changepacks/changepack_log_qPizzaodAj-f1Uz8PVvqE.json @@ -0,0 +1,7 @@ +{ + "changes": { + "Cargo.toml": "Patch" + }, + "note": "Catch first-entry animation flashes, improve Figma comparison diagnostics and record MCP failure outcomes", + "date": "2026-11-20T00:43:07.731450300Z" +} \ No newline at end of file diff --git a/crates/devup-mcp-visual/src/lib.rs b/crates/devup-mcp-visual/src/lib.rs index ff5d8119..1cb1729b 100644 --- a/crates/devup-mcp-visual/src/lib.rs +++ b/crates/devup-mcp-visual/src/lib.rs @@ -29,6 +29,15 @@ pub enum VisualStatus { InvalidDimensions, } +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PixelBounds { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct VisualReport { @@ -42,6 +51,16 @@ pub struct VisualReport { pub max_changed_ratio: f64, pub channel_tolerance: u8, pub max_channel_delta: u8, + /// Mean of each pixel's largest absolute RGBA channel delta (0..255). + #[serde(default)] + pub mean_max_channel_delta: Option, + /// Mean signed Rec. 709 channel-weighted difference (actual - reference) + /// over pixels opaque in both images, in 0..255 channel units. + #[serde(default)] + pub mean_luminance_delta: Option, + /// Smallest rectangle enclosing pixels above the channel tolerance. + #[serde(default)] + pub changed_bounds: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub diff_path: Option, } @@ -127,6 +146,9 @@ pub fn compare_png_bytes( max_changed_ratio: options.max_changed_ratio, channel_tolerance: options.channel_tolerance, max_channel_delta: 0, + mean_max_channel_delta: None, + mean_luminance_delta: None, + changed_bounds: None, diff_path: None, }, None, @@ -135,6 +157,10 @@ pub fn compare_png_bytes( let mut changed_pixels = 0_u64; let mut max_channel_delta = 0_u8; + let mut delta_sum = 0_u64; + let mut opaque_pixels = 0_u64; + let mut luminance_delta_sum = 0_i64; + let (mut left, mut top, mut right, mut bottom) = (reference.width(), reference.height(), 0, 0); let mut diff = include_diff.then(|| { ImageBuffer::from_pixel( reference.width(), @@ -142,8 +168,7 @@ pub fn compare_png_bytes( Rgba::([0, 0, 0, 0]), ) }); - for (index, (reference_pixel, actual_pixel)) in - reference.pixels().zip(actual.pixels()).enumerate() + for ((x, y, reference_pixel), actual_pixel) in reference.enumerate_pixels().zip(actual.pixels()) { let delta = reference_pixel .0 @@ -153,13 +178,23 @@ pub fn compare_png_bytes( .max() .unwrap_or(0); max_channel_delta = max_channel_delta.max(delta); + delta_sum += u64::from(delta); + if reference_pixel[3] == 255 && actual_pixel[3] == 255 { + opaque_pixels += 1; + for (channel, weight) in [2126_i64, 7152, 722].into_iter().enumerate() { + luminance_delta_sum += weight + * (i64::from(actual_pixel[channel]) - i64::from(reference_pixel[channel])); + } + } if delta <= options.channel_tolerance { continue; } changed_pixels += 1; + left = left.min(x); + top = top.min(y); + right = right.max(x); + bottom = bottom.max(y); if let Some(diff) = &mut diff { - let x = index as u32 % reference.width(); - let y = index as u32 / reference.width(); diff.put_pixel(x, y, Rgba::([255, 0, 0, 255])); } } @@ -194,6 +229,16 @@ pub fn compare_png_bytes( max_changed_ratio: options.max_changed_ratio, channel_tolerance: options.channel_tolerance, max_channel_delta, + mean_max_channel_delta: (total_pixels > 0) + .then(|| delta_sum as f64 / total_pixels as f64), + mean_luminance_delta: (opaque_pixels > 0) + .then(|| luminance_delta_sum as f64 / (10_000.0 * opaque_pixels as f64)), + changed_bounds: (changed_pixels > 0).then(|| PixelBounds { + x: left, + y: top, + width: right - left + 1, + height: bottom - top + 1, + }), diff_path: None, }, diff_png, diff --git a/crates/devup-mcp-visual/tests/compare.rs b/crates/devup-mcp-visual/tests/compare.rs index 2684458d..d031d920 100644 --- a/crates/devup-mcp-visual/tests/compare.rs +++ b/crates/devup-mcp-visual/tests/compare.rs @@ -60,6 +60,16 @@ fn exact_and_changed_pngs_report_deterministic_metrics_and_diff() -> anyhow::Res assert_eq!(report.changed_pixels, 2); assert_eq!(report.total_pixels, 8); assert_eq!(report.changed_ratio, Some(0.25)); + assert_eq!(report.mean_max_channel_delta, Some(63.75)); + assert_eq!( + report.changed_bounds, + Some(devup_mcp_visual::PixelBounds { + x: 1, + y: 0, + width: 2, + height: 1, + }) + ); assert!(diff.exists()); std::fs::remove_dir_all(root)?; Ok(()) diff --git a/crates/devup-mcp/src/server/completion.rs b/crates/devup-mcp/src/server/completion.rs index fef0a7dc..d0fc6623 100644 --- a/crates/devup-mcp/src/server/completion.rs +++ b/crates/devup-mcp/src/server/completion.rs @@ -41,6 +41,45 @@ pub struct CompletionInput { pub routes: Vec, #[serde(default = "widths")] pub widths: Vec, + /// Affected UI states that must have measured passing regression checks. + #[serde(default)] + pub required_regressions: Vec, + /// Explicit affected Figma page or section capture targets. + #[serde(default)] + pub required_visual_states: Vec, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = json!({"not": {}})))] +pub struct RequiredRegression { + pub route_path: String, + pub screen_id: String, + pub width: u32, + #[schemars(extend("enum" = ["sticky-header", "inquiry", "image-handoff", "font-stability"]))] + pub kind: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = json!({"not": {}})))] +pub struct RequiredVisualState { + pub route_path: String, + pub screen_id: String, + pub width: u32, + pub node_id: String, +} + +impl RequiredVisualState { + fn key(&self) -> (String, String, u32, String) { + (self.route_path.clone(), self.screen_id.clone(), self.width, self.node_id.clone()) + } +} + +impl RequiredRegression { + fn key(&self) -> (String, String, u32, String) { + (self.route_path.clone(), self.screen_id.clone(), self.width, self.kind.clone()) + } } #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -367,6 +406,8 @@ pub(super) async fn evaluate( || input.behavior_plan_paths.len() > 1000 || input.routes.len() > 1000 || input.static_bindings.len() > 10000 + || input.required_regressions.len() > 1000 + || input.required_visual_states.len() > 1000 { return Err(invalid( "Completion requires one to eight bounded widths, at most sixty audits, one thousand behavior plans/routes and ten thousand static binding decisions.", @@ -473,6 +514,10 @@ pub(super) async fn evaluate( routes.extend(values(&plan, "routes").filter_map(|r| r["url"].as_str().map(str::to_owned))); } let mut covered = BTreeSet::new(); + let mut regression_covered = BTreeSet::new(); + let mut expected_visual_states = BTreeSet::new(); + let mut measured_visual_states = BTreeSet::new(); + let mut visual_node_states = BTreeSet::new(); let mut required_visual = BTreeSet::new(); let mut visual_covered = BTreeSet::new(); let mut visual_results = Vec::new(); @@ -507,10 +552,21 @@ pub(super) async fn evaluate( policy, artifacts).await; let visual_pass = result["verdict"] == "pass"; audit_ok &= visual_pass; + if visual_pass && matches!(comparison["class"].as_str(), Some("page-visual" | "section-visual")) + && let (Some(route), Some(screen), Some(width), Some(node)) = ( + comparison["routePath"].as_str(), comparison["screen"].as_str(), + comparison["viewport"]["width"].as_u64(), comparison["nodeId"].as_str() + ) + { + visual_node_states.insert((route.to_owned(), screen.to_owned(), width as u32, node.to_owned())); + } if visual_pass && comparison["class"] == "page-visual" && let (Some(route), Some(width)) = (comparison["routePath"].as_str(), comparison["viewport"]["width"].as_u64()) { visual_covered.insert((route.to_owned(), width as u32)); + if let Some(screen) = comparison["screen"].as_str() { + measured_visual_states.insert((route.to_owned(), screen.to_owned(), width as u32)); + } } visual_results.push(result); } @@ -521,6 +577,21 @@ pub(super) async fn evaluate( let drawn = screen["figma"]["drawnWidths"].as_array(); if drawn.is_none_or(|v| v.is_empty() || v.iter().any(|w| w.as_u64() == Some(width))) { required_visual.insert((route.to_owned(), width as u32)); + if screen["figma"].is_object() + && let Some(id) = screen["id"].as_str() + { + expected_visual_states.insert((route.to_owned(), id.to_owned(), width as u32)); + } + } + if let Some(screen_id) = screen["id"].as_str() { + for check in values(screen, "checks").filter(|check| { + check["kind"] == "regression" && check["unavailableReason"].is_null() + && check["widths"].as_array().is_none_or(|list| list.is_empty() || list.iter().any(|w| w.as_u64() == Some(width))) + }) { + if let Some(kind) = check["regression"]["kind"].as_str() { + regression_covered.insert((route.to_owned(), screen_id.to_owned(), width as u32, kind.to_owned())); + } + } } let kinds = values(screen, "checks") .filter(|check| { @@ -561,13 +632,23 @@ pub(super) async fn evaluate( .cloned() .collect::>(); let missing_visual = required_visual.difference(&visual_covered).cloned().collect::>(); + let missing_visual_states = expected_visual_states.difference(&measured_visual_states).cloned().collect::>(); + let missing_regressions = input.required_regressions.iter() + .filter(|requirement| !regression_covered.contains(&requirement.key())) + .collect::>(); + let missing_visual_nodes = input.required_visual_states.iter() + .filter(|requirement| !visual_node_states.contains(&requirement.key())) + .collect::>(); let browser_verified = implemented && audit_ok && !routes.is_empty() && missing_routes.is_empty() && missing_motion.is_empty() && !required_visual.is_empty() - && missing_visual.is_empty(); + && missing_visual.is_empty() + && missing_visual_states.is_empty() + && missing_visual_nodes.is_empty() + && missing_regressions.is_empty(); let mut data = json!({"sourceMatched":false,"apiVerified":false,"dbVerified":false,"coveredBindingIds":[]}); if let (Some(plan_path), Some(receipt_path)) = (&input.data_plan_path, &input.data_receipt_path) { @@ -620,7 +701,7 @@ pub(super) async fn evaluate( json!({"kind":"devup-completion-receipt","schemaVersion":1,"sourceDigest":source_digest,"sourceFileCount":files.len(),"sourceScope":"project-source-and-public-assets","stage":stage,"done":data_verified,"reportAllowed":data_verified, "stages":{"generated":generated,"implemented":implemented,"browserVerified":browser_verified,"dataVerified":data_verified}, "requiredMotionIds":required_motion,"requiredBindingIds":required_bindings,"staticBindingDecisions":input.static_bindings, - "blockers":{"incompleteBehaviorCoverage":truncated,"missingChecks":missing_checks,"missingRoutesOrWidths":missing_routes,"missingVisualComparisons":missing_visual,"missingMotion":missing_motion,"missingBindings":missing_bindings}, + "blockers":{"incompleteBehaviorCoverage":truncated,"missingChecks":missing_checks,"missingRoutesOrWidths":missing_routes,"missingVisualComparisons":missing_visual,"missingVisualStates":missing_visual_states,"missingVisualNodes":missing_visual_nodes,"missingRegressions":missing_regressions,"missingMotion":missing_motion,"missingBindings":missing_bindings}, "audits":audit_results,"visualResults":visual_results,"dataEvidence":data,"dataVerificationScope":if required_bindings.is_empty(){"not-required"}else{"isolated-database-snapshots"},"input":input, "trust":"Command exits, browser measurements and SQL rows are executor-observed; source digests, plan/report bindings and referenced artifact hashes are independently rechecked. A generated export or a caller success boolean never establishes application completion."}), ) diff --git a/crates/devup-mcp/src/server/completion_tests.rs b/crates/devup-mcp/src/server/completion_tests.rs index 230facac..9d8be9fa 100644 --- a/crates/devup-mcp/src/server/completion_tests.rs +++ b/crates/devup-mcp/src/server/completion_tests.rs @@ -69,6 +69,8 @@ fn fixture() -> (std::path::PathBuf, OutputPolicy, CompletionInput) { static_bindings: BTreeMap::new(), routes: vec!["/".into()], widths: vec![360], + required_regressions: vec![], + required_visual_states: vec![], }; (root, policy, input) } @@ -372,6 +374,24 @@ async fn source_bound_static_checks_cannot_replace_figma_visuals() { input.visual_environments.insert(comparison_id, serde_json::from_value(json!({"tsxResource":{"uri":"devup://artifact/test/tsx","sha256":"a".repeat(64)},"themePath":"devup.json","assetDirectory":"public/images","devupUiVersion":"test","fontManifest":[{"family":"Test","sha256":"b".repeat(64)}]})).unwrap()); let result = write(&input, &policy, &store, None).await.unwrap(); assert_eq!(result["stage"], "data-verified", "{result}"); + let mut known = input.clone(); + known.required_visual_states.push(RequiredVisualState { + route_path: "/".into(), screen_id: "home".into(), width: 360, node_id: "1:1".into(), + }); + assert_eq!(evaluate(&known, &policy, &store).await.unwrap()["reportAllowed"], true); + + let mut required = input.clone(); + required.required_visual_states.push(RequiredVisualState { + route_path:"/".into(), screen_id:"scrolled".into(), width:360, node_id:"1:1".into(), + }); + required.required_regressions.push(RequiredRegression { + route_path:"/".into(), screen_id:"home".into(), width:360, kind:"sticky-header".into(), + }); + let missing = evaluate(&required, &policy, &store).await.unwrap(); + assert_eq!(missing["reportAllowed"], false); + assert_eq!(missing["blockers"]["missingVisualNodes"][0]["screenId"], "scrolled"); + assert_eq!(missing["blockers"]["missingRegressions"][0]["kind"], "sticky-header"); + // The one receipt that may be reported is the one that carries the offer. assert!(super::super::skills::marks_completion("devup_runtime_audit", "completion", &result)); assert!(!super::super::skills::marks_completion("devup_runtime_audit", "ingest", &result)); diff --git a/crates/devup-mcp/src/server/diagnostics/response_diagnostics.rs b/crates/devup-mcp/src/server/diagnostics/response_diagnostics.rs index 587f0894..288d08e1 100644 --- a/crates/devup-mcp/src/server/diagnostics/response_diagnostics.rs +++ b/crates/devup-mcp/src/server/diagnostics/response_diagnostics.rs @@ -58,10 +58,10 @@ pub fn connection_report( "Reading through the Devup Bridge plugin: no login needed and no Figma allowance spent." } Some(ActivePath::Direct) if bridge_blocked => { - "Reading through the metered direct path (Figma allowance is spent). The Devup Bridge plugin is not reachable from this process; this is not a server failure - paths.bridge.reason says why." + "The metered direct path is available. Direct reads count against Figma usage limits. The Devup Bridge plugin is not reachable from this process; this is not a server failure - paths.bridge.reason says why." } Some(ActivePath::Direct) => { - "Reading through the metered direct path (Figma allowance is spent). No Devup Bridge plugin is attached; running it on the file avoids the cost." + "The metered direct path is available. Direct reads count against Figma usage limits. No Devup Bridge plugin is attached; running it on the file avoids the cost." } None => "Neither the Devup Bridge plugin nor the direct path can serve a read right now.", }; diff --git a/crates/devup-mcp/src/server/diagnostics/tests.rs b/crates/devup-mcp/src/server/diagnostics/tests.rs index 82a95f2e..e274b0e3 100644 --- a/crates/devup-mcp/src/server/diagnostics/tests.rs +++ b/crates/devup-mcp/src/server/diagnostics/tests.rs @@ -262,7 +262,9 @@ mod tests { json!(["url"]) ); let summary = direct_only["summary"].as_str().unwrap(); - assert!(summary.contains("metered direct path"), "{summary}"); + assert!(summary.contains("metered direct path is available"), "{summary}"); + assert!(summary.contains("count against Figma usage limits"), "{summary}"); + assert!(!summary.contains("allowance is spent"), "{summary}"); assert!(!summary.contains("disconnected"), "{summary}"); assert!( bridge_only["summary"] diff --git a/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs b/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs index 55f99adb..bddeaccc 100644 --- a/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs +++ b/crates/devup-mcp/src/server/mod_parts/exploration_and_responses.rs @@ -770,7 +770,7 @@ impl ServerHandler for DevupServer { let mut response = match self.tool_router.call(call).await { Ok(response) => response, Err(error) if error.data.as_ref().and_then(|d| d.get("code")).is_some() => { - return Ok(structured_tool_error(error).into()); + structured_tool_error(error).into() } Err(error) => return Err(with_error_identity(error)), }; @@ -791,7 +791,10 @@ impl ServerHandler for DevupServer { )); } } - record.finish(!matches!(&response, rmcp::model::CallToolResponse::Complete(result) if result.is_error == Some(true))); + match &response { + rmcp::model::CallToolResponse::Complete(result) => record.finish_result(result), + _ => record.finish(true), + } Ok(response) } diff --git a/crates/devup-mcp/src/server/runtime_audit.rs b/crates/devup-mcp/src/server/runtime_audit.rs index 6c32cb3a..9856b33e 100644 --- a/crates/devup-mcp/src/server/runtime_audit.rs +++ b/crates/devup-mcp/src/server/runtime_audit.rs @@ -14,6 +14,8 @@ // Source sections share this module to preserve privacy and test names. include!("runtime_audit/inputs_and_capture.rs"); include!("runtime_audit/motion_validation.rs"); +include!("runtime_audit/regression.rs"); +include!("runtime_audit/check_validation.rs"); include!("runtime_audit/motion_evidence.rs"); include!("runtime_audit/write_plan.rs"); include!("runtime_audit/capture_comparison.rs"); diff --git a/crates/devup-mcp/src/server/runtime_audit/capture_comparison.rs b/crates/devup-mcp/src/server/runtime_audit/capture_comparison.rs index cd0c9220..2c9ef0f6 100644 --- a/crates/devup-mcp/src/server/runtime_audit/capture_comparison.rs +++ b/crates/devup-mcp/src/server/runtime_audit/capture_comparison.rs @@ -46,6 +46,7 @@ fn capture_comparison( "actual": shot.path, "reference": {"artifactId": reference.artifact_id, "assetId": reference.asset_id}, "threshold": threshold, + "maxLuminanceDelta": reference.max_luminance_delta, "diffPath": diff_path(&shot.path, &id), }, }, diff --git a/crates/devup-mcp/src/server/runtime_audit/check_validation.rs b/crates/devup-mcp/src/server/runtime_audit/check_validation.rs new file mode 100644 index 00000000..6d0d3277 --- /dev/null +++ b/crates/devup-mcp/src/server/runtime_audit/check_validation.rs @@ -0,0 +1,225 @@ +fn validate_check(check: &CheckInput) -> Result<(), DevupError> { + if !check.allowed_marquees.is_empty() { + if check.kind != "no-clipped-content" || check.allowed_marquees.len()>16 { + return Err(invalid("allowedMarquees is bounded to 16 selectors on no-clipped-content checks.")); + } + for selector in &check.allowed_marquees { bounded_text("allowedMarquees selector",selector)?; } + } + if let Some(reason) = &check.unavailable_reason { + return bounded_text("unavailableReason", reason); + } + let needs = |subject: bool, container: bool| -> Result<(), DevupError> { + if subject != check.subject.is_some() || container != check.container.is_some() { + return Err(invalid(format!( + "A {} check takes {}subject and {}container.", + check.kind, + if subject { "a " } else { "no " }, + if container { "a " } else { "no " }, + ))); + } + Ok(()) + }; + if check.kind == "motion" { + needs(false, false)?; + return validate_motion(check.motion.as_ref()); + } + match check.kind.as_str() { + "regression" => { + needs(false, false)?; + let config = check.regression.as_ref().ok_or_else(|| invalid("regression requires its browser contract."))?; + validate_regression(config)?; + } + "data-binding" => { + needs(false, false)?; + let config=check.data_binding.as_ref().ok_or_else(||invalid("data-binding requires dataBinding configuration."))?; + super::data_verification::validate_config(config)?; + } + "links-resolve" | "no-horizontal-overflow" | "page-health" | "no-clipped-content" => { + needs(false, false)? + } + "visible" | "view-transition" | "hidden" => needs(true, false)?, + "stale-resources" | "styles-applied" | "markup" => needs(false, false)?, + "no-clipped-text" | "no-low-contrast-text" | "image-loaded" | "native-appearance" + | "input-focus" => { + if check.container.is_some() { + return Err(invalid(format!( + "A {} check takes no container.", + check.kind + ))); + } + } + "bounds" => { + needs(true, true)?; + if check.tolerance_px.is_some() { + return Err(invalid( + "A bounds check is exact (half a pixel of rounding); it takes no tolerancePx. A mismatch is code drift or a converter bug, never noise.", + )); + } + let Some(expected) = &check.expected else { + return Err(invalid( + "A bounds check needs expected {x, y, width, height}.", + )); + }; + if [expected.x, expected.y, expected.width, expected.height] + .iter() + .any(|value| !value.is_finite() || value.abs() > 100_000.0) + || expected.width < 0.0 + || expected.height < 0.0 + { + return Err(invalid( + "bounds expected values must be finite px, width and height nonnegative.", + )); + } + } + "interaction" => { + // Without a subject it sweeps every visible link and button. + if check.container.is_some() { + return Err(invalid("An interaction check takes no container.")); + } + if !matches!(check.state.as_deref(), Some("hover" | "focus")) { + return Err(invalid("An interaction check needs state hover or focus.")); + } + } + "capture" => { + needs(true, false)?; + let Some(reference) = &check.reference else { + return Err(invalid( + "A capture check needs reference {scope, artifactId, assetId}.", + )); + }; + if !matches!(reference.scope.as_str(), "section" | "asset") { + return Err(invalid("capture reference.scope must be section or asset.")); + } + bounded_text("reference.artifactId", &reference.artifact_id)?; + bounded_text("reference.assetId", &reference.asset_id)?; + if reference + .threshold + .is_some_and(|value| !(0.0..=1.0).contains(&value)) + { + return Err(invalid("reference.threshold must be between 0 and 1.")); + } + if reference.max_luminance_delta.is_some_and(|limit| !(0.0..=255.0).contains(&limit)) { + return Err(invalid("reference.maxLuminanceDelta must be between 0 and 255.")); + } + } + "dimensions" => { + needs(true, false)?; + if check.tolerance_px.is_none() + || check.figma_dimensions.is_empty() + || !matches!(check.measure.as_deref(), None | Some("box")) + { + return Err(invalid( + "A dimensions check needs tolerancePx, figmaDimensions and measure box.", + )); + } + } + "text-align" => { + needs(true, false)?; + if !matches!( + check.edge.as_deref(), + Some("left" | "right" | "center" | "justify") + ) { + return Err(invalid( + "A text-align check needs edge left, right, center or justify.", + )); + } + } + "sequence-order" => needs(false, false)?, + "section-layout" => { + if check.subject.is_some() { + needs(true, true)?; + } else { + needs(false, false)?; + } + } + "rendered-completeness" => { + needs(false, false)?; + let Some(completeness) = &check.completeness else { + return Err(invalid( + "A rendered-completeness check needs completeness {frameHeight, sections, images}.", + )); + }; + validate_completeness(completeness)?; + if check.widths.len() != 1 { + return Err(invalid( + "A rendered-completeness check holds one frame, so it names exactly one width.", + )); + } + } + "contained" | "spans" => needs(true, true)?, + "aligned" => { + needs(true, true)?; + if !matches!(check.edge.as_deref(), Some("left" | "right" | "center")) { + return Err(invalid( + "An aligned check needs edge left, right or center.", + )); + } + } + other => return Err(invalid(format!("Unknown check kind {other}."))), + } + for (field, present, kind) in [ + ("dataBinding",check.data_binding.is_some(),"data-binding"), + ("regression", check.regression.is_some(), "regression"), + ("expected", check.expected.is_some(), "bounds"), + ("state", check.state.is_some(), "interaction"), + ("reference", check.reference.is_some(), "capture"), + ( + "completeness", + check.completeness.is_some(), + "rendered-completeness", + ), + ] { + if present && check.kind != kind { + return Err(invalid(format!("{field} is only valid for {kind} checks."))); + } + } + if let Some(node_id) = &check.node_id { + bounded_text("checks[].nodeId", node_id)?; + } + if check.kind != "dimensions" && !check.figma_dimensions.is_empty() { + return Err(invalid( + "figmaDimensions is only valid for dimensions checks.", + )); + } + let mut widths = std::collections::BTreeSet::new(); + for reference in &check.figma_dimensions { + bounded_text("figmaDimensions.artifactId", &reference.artifact_id)?; + bounded_text("figmaDimensions.nodeId", &reference.node_id)?; + if !widths.insert(reference.viewport_width) { + return Err(invalid( + "A dimensions check needs at most one explicit reference per width.", + )); + } + } + for (field, locator) in [("subject", &check.subject), ("container", &check.container)] { + if let Some(locator) = locator { + validate_locator(&format!("checks[].{field}"), locator, true)?; + } + } + match check.measure.as_deref() { + None | Some("box") => {} + Some("painted-mask") if check.subject.is_some() => {} + Some(other) => { + return Err(invalid(format!( + "measure {other} is not box, or painted-mask on a check with a subject." + ))); + } + } + for value in [check.offset_px, check.inset_px, check.tolerance_px] + .into_iter() + .flatten() + { + if !value.is_finite() || value.abs() > 10_000.0 { + return Err(invalid( + "Check offsets, insets and tolerances must be finite px values.", + )); + } + } + if check.tolerance_px.is_some_and(|value| value < 0.0) { + return Err(invalid("tolerancePx must be nonnegative.")); + } + if let Some(label) = &check.label { + bounded_text("checks[].label", label)?; + } + Ok(()) +} diff --git a/crates/devup-mcp/src/server/runtime_audit/inputs_and_capture.rs b/crates/devup-mcp/src/server/runtime_audit/inputs_and_capture.rs index a2b98dac..03a3bb8e 100644 --- a/crates/devup-mcp/src/server/runtime_audit/inputs_and_capture.rs +++ b/crates/devup-mcp/src/server/runtime_audit/inputs_and_capture.rs @@ -144,7 +144,7 @@ pub struct ScreenInput { #[serde(rename_all = "camelCase", deny_unknown_fields)] #[schemars(extend("additionalProperties" = json!({"not": {}})))] pub struct StepInput { - #[schemars(extend("enum" = ["click", "fill", "press", "back", "forward", "reload"]))] + #[schemars(extend("enum" = ["click", "fill", "press", "scroll", "back", "forward", "reload"]))] pub action: String, #[serde(default)] pub target: LocatorInput, @@ -272,11 +272,14 @@ pub struct CheckInput { /// minHeightRatio of the frame's height, every listed section and image /// renders (images decoded), and no text is invisible against what is /// painted behind it. A drawn width without a passing one is not-run. - #[schemars(extend("enum" = ["links-resolve", "no-horizontal-overflow", "contained", "aligned", "spans", "visible", "dimensions", "view-transition", "page-health", "markup", "bounds", "no-clipped-text", "interaction", "input-focus", "capture", "hidden", "rendered-completeness", "sequence-order", "section-layout", "text-align", "no-clipped-content", "styles-applied", "no-low-contrast-text", "image-loaded", "native-appearance", "stale-resources", "motion", "data-binding"]))] + #[schemars(extend("enum" = ["links-resolve", "no-horizontal-overflow", "contained", "aligned", "spans", "visible", "dimensions", "view-transition", "page-health", "markup", "bounds", "no-clipped-text", "interaction", "input-focus", "capture", "hidden", "rendered-completeness", "sequence-order", "section-layout", "text-align", "no-clipped-content", "styles-applied", "no-low-contrast-text", "image-loaded", "native-appearance", "stale-resources", "motion", "data-binding", "regression"]))] pub kind: String, /// Observe actual intermediate motion and continuity using semantic selectors. #[serde(default, skip_serializing_if = "Option::is_none")] pub motion: Option, + /// Observed header, inquiry, image handoff or delayed-font regression. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub regression: Option, /// links-resolve: confirmed URL patterns and routes found on disk. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub planned_targets: Vec, @@ -358,6 +361,9 @@ pub struct CaptureReferenceInput { /// not a filled shape where an outline was drawn. #[serde(default, skip_serializing_if = "Option::is_none")] pub threshold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + #[schemars(range(min = 0.0, max = 255.0))] + pub max_luminance_delta: Option, } /// Changed-pixel ratios that absorb anti-aliasing between Figma's renderer @@ -613,12 +619,12 @@ pub(crate) fn validate_plan(plan: &PlanInput) -> Result<(), DevupError> { } timeout("steps[].timeoutMs", step.timeout_ms)?; match (step.action.as_str(), &step.value) { - ("click" | "back" | "forward" | "reload", None) => {} + ("click" | "scroll" | "back" | "forward" | "reload", None) => {} ("fill", Some(value)) if value.chars().count() <= MAX_TEXT => {} ("press", Some(value)) if !value.is_empty() && value.chars().count() <= MAX_TEXT => {} _ => { return Err(invalid( - "A step is click, back, forward or reload (no value), or fill/press (nonempty value, at most 300 characters).", + "A step is click, scroll, back, forward or reload (no value), or fill/press (nonempty value, at most 300 characters).", )); } } @@ -691,223 +697,6 @@ pub(crate) fn validate_plan(plan: &PlanInput) -> Result<(), DevupError> { timeout("stepTimeoutMs", plan.step_timeout_ms) } -fn validate_check(check: &CheckInput) -> Result<(), DevupError> { - if !check.allowed_marquees.is_empty() { - if check.kind != "no-clipped-content" || check.allowed_marquees.len()>16 { - return Err(invalid("allowedMarquees is bounded to 16 selectors on no-clipped-content checks.")); - } - for selector in &check.allowed_marquees { bounded_text("allowedMarquees selector",selector)?; } - } - if let Some(reason) = &check.unavailable_reason { - return bounded_text("unavailableReason", reason); - } - let needs = |subject: bool, container: bool| -> Result<(), DevupError> { - if subject != check.subject.is_some() || container != check.container.is_some() { - return Err(invalid(format!( - "A {} check takes {}subject and {}container.", - check.kind, - if subject { "a " } else { "no " }, - if container { "a " } else { "no " }, - ))); - } - Ok(()) - }; - if check.kind == "motion" { - needs(false, false)?; - return validate_motion(check.motion.as_ref()); - } - match check.kind.as_str() { - "data-binding" => { - needs(false, false)?; - let config=check.data_binding.as_ref().ok_or_else(||invalid("data-binding requires dataBinding configuration."))?; - super::data_verification::validate_config(config)?; - } - "links-resolve" | "no-horizontal-overflow" | "page-health" | "no-clipped-content" => { - needs(false, false)? - } - "visible" | "view-transition" | "hidden" => needs(true, false)?, - "stale-resources" | "styles-applied" | "markup" => needs(false, false)?, - "no-clipped-text" | "no-low-contrast-text" | "image-loaded" | "native-appearance" - | "input-focus" => { - if check.container.is_some() { - return Err(invalid(format!( - "A {} check takes no container.", - check.kind - ))); - } - } - "bounds" => { - needs(true, true)?; - if check.tolerance_px.is_some() { - return Err(invalid( - "A bounds check is exact (half a pixel of rounding); it takes no tolerancePx. A mismatch is code drift or a converter bug, never noise.", - )); - } - let Some(expected) = &check.expected else { - return Err(invalid( - "A bounds check needs expected {x, y, width, height}.", - )); - }; - if [expected.x, expected.y, expected.width, expected.height] - .iter() - .any(|value| !value.is_finite() || value.abs() > 100_000.0) - || expected.width < 0.0 - || expected.height < 0.0 - { - return Err(invalid( - "bounds expected values must be finite px, width and height nonnegative.", - )); - } - } - "interaction" => { - // Without a subject it sweeps every visible link and button. - if check.container.is_some() { - return Err(invalid("An interaction check takes no container.")); - } - if !matches!(check.state.as_deref(), Some("hover" | "focus")) { - return Err(invalid("An interaction check needs state hover or focus.")); - } - } - "capture" => { - needs(true, false)?; - let Some(reference) = &check.reference else { - return Err(invalid( - "A capture check needs reference {scope, artifactId, assetId}.", - )); - }; - if !matches!(reference.scope.as_str(), "section" | "asset") { - return Err(invalid("capture reference.scope must be section or asset.")); - } - bounded_text("reference.artifactId", &reference.artifact_id)?; - bounded_text("reference.assetId", &reference.asset_id)?; - if reference - .threshold - .is_some_and(|value| !(0.0..=1.0).contains(&value)) - { - return Err(invalid("reference.threshold must be between 0 and 1.")); - } - } - "dimensions" => { - needs(true, false)?; - if check.tolerance_px.is_none() - || check.figma_dimensions.is_empty() - || !matches!(check.measure.as_deref(), None | Some("box")) - { - return Err(invalid( - "A dimensions check needs tolerancePx, figmaDimensions and measure box.", - )); - } - } - "text-align" => { - needs(true, false)?; - if !matches!( - check.edge.as_deref(), - Some("left" | "right" | "center" | "justify") - ) { - return Err(invalid( - "A text-align check needs edge left, right, center or justify.", - )); - } - } - "sequence-order" => needs(false, false)?, - "section-layout" => { - if check.subject.is_some() { - needs(true, true)?; - } else { - needs(false, false)?; - } - } - "rendered-completeness" => { - needs(false, false)?; - let Some(completeness) = &check.completeness else { - return Err(invalid( - "A rendered-completeness check needs completeness {frameHeight, sections, images}.", - )); - }; - validate_completeness(completeness)?; - if check.widths.len() != 1 { - return Err(invalid( - "A rendered-completeness check holds one frame, so it names exactly one width.", - )); - } - } - "contained" | "spans" => needs(true, true)?, - "aligned" => { - needs(true, true)?; - if !matches!(check.edge.as_deref(), Some("left" | "right" | "center")) { - return Err(invalid( - "An aligned check needs edge left, right or center.", - )); - } - } - other => return Err(invalid(format!("Unknown check kind {other}."))), - } - for (field, present, kind) in [ - ("dataBinding",check.data_binding.is_some(),"data-binding"), - ("expected", check.expected.is_some(), "bounds"), - ("state", check.state.is_some(), "interaction"), - ("reference", check.reference.is_some(), "capture"), - ( - "completeness", - check.completeness.is_some(), - "rendered-completeness", - ), - ] { - if present && check.kind != kind { - return Err(invalid(format!("{field} is only valid for {kind} checks."))); - } - } - if let Some(node_id) = &check.node_id { - bounded_text("checks[].nodeId", node_id)?; - } - if check.kind != "dimensions" && !check.figma_dimensions.is_empty() { - return Err(invalid( - "figmaDimensions is only valid for dimensions checks.", - )); - } - let mut widths = std::collections::BTreeSet::new(); - for reference in &check.figma_dimensions { - bounded_text("figmaDimensions.artifactId", &reference.artifact_id)?; - bounded_text("figmaDimensions.nodeId", &reference.node_id)?; - if !widths.insert(reference.viewport_width) { - return Err(invalid( - "A dimensions check needs at most one explicit reference per width.", - )); - } - } - for (field, locator) in [("subject", &check.subject), ("container", &check.container)] { - if let Some(locator) = locator { - validate_locator(&format!("checks[].{field}"), locator, true)?; - } - } - match check.measure.as_deref() { - None | Some("box") => {} - Some("painted-mask") if check.subject.is_some() => {} - Some(other) => { - return Err(invalid(format!( - "measure {other} is not box, or painted-mask on a check with a subject." - ))); - } - } - for value in [check.offset_px, check.inset_px, check.tolerance_px] - .into_iter() - .flatten() - { - if !value.is_finite() || value.abs() > 10_000.0 { - return Err(invalid( - "Check offsets, insets and tolerances must be finite px values.", - )); - } - } - if check.tolerance_px.is_some_and(|value| value < 0.0) { - return Err(invalid("tolerancePx must be nonnegative.")); - } - if let Some(label) = &check.label { - bounded_text("checks[].label", label)?; - } - Ok(()) -} - /// The id a plan is known by: the SHA-256 of its normalized form, so the same /// plan always has the same id and any edit gives a new one. pub(super) fn plan_id(plan: &PlanInput) -> Result { diff --git a/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs b/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs index 671e55ee..137ff41e 100644 --- a/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs +++ b/crates/devup-mcp/src/server/runtime_audit/motion_evidence.rs @@ -106,6 +106,10 @@ fn motion_evidence_row(policy: &OutputPolicy, report_dir: &Path, at: &MotionChec None => unverified.push(format!("{name}: not requested")), } } + let fast_scroll = &measured["scenarios"]["fast-scroll"]; + if fast_scroll["flash"].is_object() { + row["firstEntryFlash"] = fast_scroll["flash"].clone(); + } row["notApplicable"] = json!(names(&measured["notApplicable"])); let stagger = &measured["scenarios"]["stagger"]; if stagger["stepsMs"].is_array() { diff --git a/crates/devup-mcp/src/server/runtime_audit/regression.rs b/crates/devup-mcp/src/server/runtime_audit/regression.rs new file mode 100644 index 00000000..fd10362e --- /dev/null +++ b/crates/devup-mcp/src/server/runtime_audit/regression.rs @@ -0,0 +1,179 @@ +/// Browser contracts for UI regressions that a settled screenshot cannot prove. +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde( + tag = "kind", + rename_all = "kebab-case", + rename_all_fields = "camelCase", + deny_unknown_fields +)] +pub enum RegressionInput { + #[schemars(extend("additionalProperties" = json!({"not": {}})))] + StickyHeader { + header: String, + hero: String, + logo: String, + links: String, + scrolled_background: String, + }, + #[schemars(extend("additionalProperties" = json!({"not": {}})))] + Inquiry { + open: String, + detail: String, + description: String, + description_text: String, + inquire: String, + form: String, + choice: InquiryChoice, + fields: Vec, + submit: String, + error: String, + recipient: String, + }, + #[schemars(extend("additionalProperties" = json!({"not": {}})))] + ImageHandoff { + /// An application selector attached only once the opening action is hydrated. + ready: Option, + open: Option, + images: String, + next: Option, + /// Swipe the current image left or right instead of clicking next. + #[schemars(extend("enum" = ["left", "right"]))] + swipe: Option, + next_src: String, + }, + #[schemars(extend("additionalProperties" = json!({"not": {}})))] + FontStability { + fonts: Vec, + targets: Vec, + }, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[schemars(extend("additionalProperties" = json!({"not": {}})))] +pub struct InquiryChoice { + pub control: String, + pub value: String, + /// Custom listboxes name both the option to click and the selected label. + /// Omit both for a native select; value then names the option value. + pub option: Option, + pub selected: Option, +} + +#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +#[schemars(extend("additionalProperties" = json!({"not": {}})))] +pub struct InquiryField { + pub selector: String, + pub value: String, +} + +fn validate_regression(config: &RegressionInput) -> Result<(), DevupError> { + let text = |name, value: &str| bounded_text(name, value); + let selector = |value: &str| { + text("regression selector", value)?; + if value.contains("data-figma") || value.contains("data-source-node") { + return Err(invalid("Regression checks require application selectors.")); + } + Ok(()) + }; + match config { + RegressionInput::StickyHeader { + header, + hero, + logo, + links, + scrolled_background, + } => { + for value in [header, hero, logo, links] { + selector(value)?; + } + text("regression.scrolledBackground", scrolled_background)?; + if !scrolled_background.starts_with("rgb(") { + return Err(invalid( + "scrolledBackground requires an opaque computed rgb() color.", + )); + } + } + RegressionInput::Inquiry { + open, + detail, + description, + description_text, + inquire, + form, + choice, + fields, + submit, + error, + recipient, + } => { + for value in [ + open, + detail, + description, + inquire, + form, + &choice.control, + submit, + error, + ] { + selector(value)?; + } + for value in [&choice.option, &choice.selected].into_iter().flatten() { + selector(value)?; + } + if (choice.option.is_some() && choice.selected.is_none()) + || !(1..=8).contains(&fields.len()) + { + return Err(invalid( + "Inquiry needs 1-8 fields and, for a custom select, both option and selected selectors.", + )); + } + text("regression.descriptionText", description_text)?; + text("regression.choice.value", &choice.value)?; + text("regression.recipient", recipient)?; + for field in fields { + selector(&field.selector)?; + text("regression field value", &field.value)?; + } + } + RegressionInput::ImageHandoff { + ready, + open, + images, + next, + swipe, + next_src, + } => { + if next.is_some() == swipe.is_some() + || swipe + .as_deref() + .is_some_and(|direction| !matches!(direction, "left" | "right")) + { + return Err(invalid( + "Image handoff requires exactly one of next or swipe (left/right).", + )); + } + for value in [ready, open, next].into_iter().flatten() { + selector(value)?; + } + selector(images)?; + validate_route("regression.nextSrc", next_src)?; + } + RegressionInput::FontStability { fonts, targets } => { + if !(1..=8).contains(&fonts.len()) || !(1..=16).contains(&targets.len()) { + return Err(invalid( + "Font stability needs 1-8 font paths and 1-16 first-viewport selectors.", + )); + } + for path in fonts { + validate_route("regression font path", path)?; + } + for value in targets { + selector(value)?; + } + } + } + Ok(()) +} diff --git a/crates/devup-mcp/src/server/runtime_audit/tests.rs b/crates/devup-mcp/src/server/runtime_audit/tests.rs index 164f3789..96f706af 100644 --- a/crates/devup-mcp/src/server/runtime_audit/tests.rs +++ b/crates/devup-mcp/src/server/runtime_audit/tests.rs @@ -61,7 +61,7 @@ mod tests { ) .await .unwrap(); - assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 15); + assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 16); let imported = std::process::Command::new("node") .args(["--input-type=module", "-e", "await import('./run.mjs')"]) .current_dir(dir.join("runner")) diff --git a/crates/devup-mcp/src/server/runtime_audit/write_plan.rs b/crates/devup-mcp/src/server/runtime_audit/write_plan.rs index 9c1513cc..db3060b8 100644 --- a/crates/devup-mcp/src/server/runtime_audit/write_plan.rs +++ b/crates/devup-mcp/src/server/runtime_audit/write_plan.rs @@ -71,6 +71,7 @@ fn write_plan( for (name, bytes) in [ ("source-digest.mjs", include_bytes!("../../../../../harness/runtime-audit/source-digest.mjs").as_slice()), ("record-project-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/record-project-checks.mjs").as_slice()), + ("regression-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/regression-checks.mjs").as_slice()), ("motion-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/motion-checks.mjs").as_slice()), ("reveal-checks.mjs", include_bytes!("../../../../../harness/runtime-audit/reveal-checks.mjs").as_slice()), ( diff --git a/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md b/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md index 55d64b84..8a3b130e 100644 --- a/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md +++ b/crates/devup-mcp/src/server/skills/devfive-frontend/references/animation.md @@ -187,6 +187,15 @@ that change (`transition="opacity .2s, transform .2s"`), switched off with - **Images.** Images inside a revealed block reserve their size. A slow or failed image must not hold the block hidden or shift it when it arrives. +For timed scroll entrances, prepare only offscreen elements for motion. Once +an element is visible at its resting position, keep it there if hydration or +the observer is late. The first rendered frame in the viewport must already +be continuous with the entrance. Ready content stays visible with JavaScript +disabled or reduced motion enabled. A sticky header uses a short color +transition between states and a consistent height; it has no entrance +translation. Check the reverse scroll direction and the reduced-motion +variant. + ## 4. Verify the motion, not the final screenshot A correct final frame says nothing about the animation. For every motion you diff --git a/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md b/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md index 1259b45c..be6a434f 100644 --- a/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md +++ b/crates/devup-mcp/src/server/skills/devup-implementation-plan/SKILL.md @@ -636,6 +636,33 @@ evidence and replaces the question it would otherwise take: - `visualThresholds` sets the changed-pixel ratio the comparisons allow: `{ "page": 0.03, "section": 0.03, "asset": 0.05, "nodes": { "12:34": 0.08 } }`. +**After a follow-up UI edit**, use the same Figma and browser completion gate as +the first implementation, even for CSS-only changes. Recheck the affected +states of every route that shares the component, at the original designed +widths. For a sticky header, capture the over-hero and scrolled states, check +logo visibility and home navigation from both, and verify background blending +in both directions and the under-edge divider in each settled state. Keep +approved deviations explicit (for example a logo that the user requests in +the header's over-hero variant). Preserve differing screenshot evidence and +explain it using the affected state, region and rendered styles. + +When the design contains details or forms, navigate to them in the browser. +Compare text and action availability after clicking the entry control, exercise +the actual selection/submit path, and check computed focus and pressed states. +For image transitions, include a delayed response and verify the visible +image remains usable until its successor decodes. For font changes, compare +the first viewport geometry on a cold load and while font responses are +delayed; preload only fonts actually needed by the initial viewport. + +Bind these observed behaviors in the runtime audit plan instead of relying on +a screenshot to prove them. Use regression contracts for sticky headers, +artwork-to-inquiry flows, delayed image handoffs, and first-viewport font +stability. Put affected route/screen/width contracts in requiredRegressions, +and exact Figma state comparisons in requiredVisualStates on completion. +Use a scroll step and a native-section PNG for a scrolled header. When the +hero appears lighter or darker, compare the same Figma section and examine +the signed luminance delta. Use an approved brightness bound where applicable. + Connected URLs: run `links-resolve` at every width. Each same-origin anchor contributes source URL, accessible label, href, resolved pathname and width to `linkTable` (also Markdown in `finalReport`). GET each distinct target once, including concrete dynamic hrefs, and reject HTTP failures, error pages and `unplanned-target` URLs absent from the confirmed plan and existing routes. Any failing link row blocks done. ## Staged split, contract-first data and decisions diff --git a/crates/devup-mcp/src/server/skills/devup-retro/SKILL.md b/crates/devup-mcp/src/server/skills/devup-retro/SKILL.md index 0fa0ecf1..79e16aed 100644 --- a/crates/devup-mcp/src/server/skills/devup-retro/SKILL.md +++ b/crates/devup-mcp/src/server/skills/devup-retro/SKILL.md @@ -31,7 +31,7 @@ confirms the review list. `server.commit`, `server.buildId`), this server process's devup-mcp call log with timestamps (`callLog`), the `.feedback/` folder state (`feedback`), the surface list (`surfaces`) and where release notes live (`releases`). - The call log only covers this server process: after a reconnect or in a + For a failed call, use the retained errorCode and the original error response when visible. A completed visual comparison can separately carry verdict=inconclusive; this is a missing verification result, not a tool execution error. The call log only covers this server process: after a reconnect or in a resumed session it is partial, and `callLog.note` says so. It is an aid for ordering, never the evidence itself. 2. Find the starting point: the first devup-mcp call of the work under review diff --git a/crates/devup-mcp/src/server/skills/manifest.json b/crates/devup-mcp/src/server/skills/manifest.json index 7554892e..c4ea20df 100644 --- a/crates/devup-mcp/src/server/skills/manifest.json +++ b/crates/devup-mcp/src/server/skills/manifest.json @@ -81,8 +81,8 @@ }, { "path": "references/animation.md", - "bytes": 13308, - "sha256": "de275d513330b2a84834be13226c63115ad591cfc5922858110a7cf79dfe0e5e" + "bytes": 13837, + "sha256": "5cac2098bd4be5302e0b018e955b5ceb8ae83810d511b9bf99161b601d4d7a0e" } ], "sourceUrl": "https://github.com/dev-five-git/devup-mcp/blob/HEAD/crates/devup-mcp/src/server/skills/devfive-frontend", @@ -99,8 +99,8 @@ "documents": [ { "path": "SKILL.md", - "bytes": 46928, - "sha256": "eeef6ee8744deccda24908be0d94b0016e4d4364e172903adf1745422b6ca511" + "bytes": 48735, + "sha256": "5fe7b752fb5f830e8efda50cb33e1e6ae23db22d6725544139d4fc70401f83d3" } ], "sourceUrl": "https://github.com/dev-five-git/devup-mcp/blob/HEAD/crates/devup-mcp/src/server/skills/devup-implementation-plan", @@ -135,8 +135,8 @@ "documents": [ { "path": "SKILL.md", - "bytes": 10021, - "sha256": "a307ae31c9272fa921c193cfb522a2f3ac99d73eeb9c2fed174c9614a0b692d3" + "bytes": 10253, + "sha256": "2e22d128d8210eeabb40fe2fa3eb71544e031b7ff2d3855387b78d98928be528" } ], "sourceUrl": "https://github.com/dev-five-git/devup-mcp/blob/HEAD/crates/devup-mcp/src/server/skills/devup-retro", diff --git a/crates/devup-mcp/src/server/skills/retro.rs b/crates/devup-mcp/src/server/skills/retro.rs index 6ac55650..af6db1a9 100644 --- a/crates/devup-mcp/src/server/skills/retro.rs +++ b/crates/devup-mcp/src/server/skills/retro.rs @@ -40,6 +40,8 @@ struct CallEntry { at_ms: u64, duration_ms: u64, ok: bool, + error_code: Option, + verdict: Option, } #[derive(Debug, Default)] @@ -105,6 +107,8 @@ impl CallLog { at_ms: now_ms(), duration_ms: 0, ok: false, + error_code: None, + verdict: None, }, started: std::time::Instant::now(), } @@ -123,6 +127,12 @@ impl CallLog { "durationMs": entry.duration_ms, "ok": entry.ok, }); + if let Some(code) = &entry.error_code { + call["errorCode"] = serde_json::json!(code); + } + if let Some(verdict) = &entry.verdict { + call["verdict"] = serde_json::json!(verdict); + } if let Some(action) = &entry.action { call["action"] = serde_json::json!(action); } @@ -144,7 +154,7 @@ impl CallLog { "note": "Calls this devup-mcp process served, oldest first, UTC. A reconnect, a \ restart or a resumed session starts an empty log, so a short log is not \ evidence that nothing was called: the conversation is the record, and this \ - only helps order it. Arguments' contents and results are not kept.", + only helps order it. Only a stable error code or visual verdict is retained from the result.", }) } } @@ -153,6 +163,23 @@ impl CallRecord { pub fn finish(&mut self, ok: bool) { self.entry.ok = ok; } + + pub fn finish_result(&mut self, result: &rmcp::model::CallToolResult) { + self.finish(result.is_error != Some(true)); + let Some(data) = &result.structured_content else { + return; + }; + if !self.entry.ok { + self.entry.error_code = data["error"]["code"].as_str() + .filter(|code| code.starts_with("DEVUP_") && code.len() <= 64 + && code.bytes().all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit() || byte == b'_')) + .map(str::to_owned); + } else if self.entry.tool == "devup_visual_compare" { + self.entry.verdict = data["verdict"].as_str() + .filter(|verdict| matches!(*verdict, "pass" | "fail" | "inconclusive")) + .map(str::to_owned); + } + } } impl Drop for CallRecord { diff --git a/crates/devup-mcp/src/server/skills/retro_tests.rs b/crates/devup-mcp/src/server/skills/retro_tests.rs index ae38b40c..7d116075 100644 --- a/crates/devup-mcp/src/server/skills/retro_tests.rs +++ b/crates/devup-mcp/src/server/skills/retro_tests.rs @@ -147,6 +147,26 @@ language:"), "a blank argument is not passed on"); assert_eq!(report["calls"][0]["seq"], 8); } + #[test] + fn retro_separates_tool_errors_from_inconclusive_comparisons() { + let log = CallLog::default(); + let mut error = crate::server::delivery::tool_result(serde_json::json!({ + "error":{"code":"DEVUP_SNAPSHOT_UNSUPPORTED","message":"private-details"} + })); + error.is_error = Some(true); + log.begin("devup_figma_export", None).finish_result(&error); + let compare = crate::server::delivery::tool_result(serde_json::json!({ + "verdict":"inconclusive","environment":{"issues":["private-details"]} + })); + log.begin("devup_visual_compare", None).finish_result(&compare); + let report = log.report(); + assert_eq!(report["calls"][0]["ok"], false); + assert_eq!(report["calls"][0]["errorCode"], "DEVUP_SNAPSHOT_UNSUPPORTED"); + assert_eq!(report["calls"][1]["ok"], true); + assert_eq!(report["calls"][1]["verdict"], "inconclusive"); + assert!(!report.to_string().contains("private-details")); + } + #[test] fn timestamps_are_utc_calendar_dates() { assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z"); diff --git a/crates/devup-mcp/src/server/text/completion.md b/crates/devup-mcp/src/server/text/completion.md index 20f0571e..05da006c 100644 --- a/crates/devup-mcp/src/server/text/completion.md +++ b/crates/devup-mcp/src/server/text/completion.md @@ -46,6 +46,16 @@ in the browser plan, or pass the explicitly agreed required widths to both. comparison ID (tsxResource, themePath, assetDirectory, devupUiVersion and fontManifest). Observed viewport, capture context, renderer and actual PNG stay bound to the audited run. Retain actual/reference/diff and thresholds. + Apply this gate to follow-up edits, including shared components and CSS-only + fixes after the initial plan was approved. List affected routes and states + before testing. Capture the updated page against the corresponding Figma + state at each drawn width and retain the fresh source-bound evidence. Record + any user-approved variation with its state and source node so a known + design difference remains visible in the report. A static Figma frame + establishes an endpoint only; measure transitions and functional actions in + the browser. If a state has no Figma reference or the verdict is + inconclusive, state the gap and use the approved acceptance criteria for + runtime evidence. A tool receipt or an old screenshot does not clear it. 5. Operational data uses a typed `data-binding` check with actual OpenAPI/model anchors, exact exported binding IDs (`nodeId::role`), explicit aggregate and landing/list/detail selectors. The runner requires an isolated disposable DB, diff --git a/crates/devup-mcp/src/server/text/devup-figma-export.md b/crates/devup-mcp/src/server/text/devup-figma-export.md index c2155413..8a2ff655 100644 --- a/crates/devup-mcp/src/server/text/devup-figma-export.md +++ b/crates/devup-mcp/src/server/text/devup-figma-export.md @@ -1,3 +1,5 @@ +For visual references, make one call per designed width: pass the exact Figma frame URL, scope: node, and outputs: ["referencePng"]. Omit frameIds and allScreens for those calls. Keep multi-width outline and responsive TSX in a separate call; an unsupported combined request returns referenceCalls and, when applicable, remainingCall. + Export a small Figma selection. outputs:[outline] returns a bounded captured tree with logical layout metrics and responseOffset/responseLimit pagination. responseFields or path use a validated field/index/exact-name-or-id grammar (e.g. nodes[name="Cards"].layout), retaining node identity and linking full omitted evidence as resources. For only explicit node dimensions, prefer devup_figma_measure, which bypasses snapshot collection and code generation; the Figma-to-code entry point. url is optional while exactly one Devup Bridge plugin is attached (devup_figma_auth status shows what is attached): omitted, or given as figma-bridge://current, the export reads the file that plugin has open and the node selected in Figma; frameIds without url name frames in it - one id is that frame, several are screens of the selected Section. Never invent a Figma file key to fill url. Asset requests: recommend 1–3 per call, maximum 6; split larger assetRequests before calling. All fresh exports return exportJob (assetJob compatibility alias) within a one-second initial wait when collection is still running, with per-call frame/root IDs, pagination and elapsed time. Slow asset calls also retain per-asset progress. Poll with jobId; use jobAction=resume when paused. Polls return compact asset rows (status, bytes, sha256, fileState, on-disk fileFacts, fileStateReason when not written); responseFields on a poll selects from its reply, e.g. exportJob.assets for full rows; assetJob only references exportJob. Generated code uses maskImage only for single-colour icons; multi-colour icons stay . Never convert an icon to a mask or recolour it by hand. Jobs retain accepted reads/bytes across client timeouts for 30 minutes in this server process, not across restart. Identical arguments recover a lost job reply. Completed results are retained for 5 minutes. Recommend 1–3 frames per call; allow at most 6 frames and 12 frame-times-output units. Budget roughly 5–20 seconds per frame-output unit (15–60 seconds per frame for three outputs) as a planning heuristic, not a guarantee: paging, complexity and throttling can exceed it and clients commonly time out at 300 seconds. Oversized selections are refused before screen collection; split frameIds into one-frame calls when isolating latency, or poll jobId. Partial per-frame projection failures retain successful frame outputs. projectionIssues always explains reported approximations, unclassified layout loss and missing generated-property provenance, even without includeDiagnostics. mappingComplete=false identifies mapping gaps; mapping-incomplete is not value loss and cannot be exact. projectionEvidence includes source fields and calculations for generated attributes. outputPathResults lists supported keys and diagnostics; frame file keys are frame::, while outputPaths reports actual committed writes. Resource responses offer nextAction.tool/arguments for same-artifact body comparison and sizeEstimate with explicit unmeasured wire overhead; coupled asset/path arguments remain together. quality.assets grades binary collection; assetSummary.description explains collection state. Merge saved batch responses offline with devup-mcp --merge-asset-batches batch1.json batch2.json for cumulative collection, unrequested, failed and conflict counts. SECTION links use two stages: receive selection_required, then run nextAction.example to export a selected screen. Asked to build pages or a site from Figma, follow the devup-implementation-plan workflow (/devup) even if not asked: it plans the URLs, updates dependencies to the latest, and adds interaction states, transitions and metadata; App Router apps may run on vinext with no next dependency. Building pages: with projectRoot, a page write (pageScaffold write, outputPaths under app/, or several frames with outputPaths) needs a confirmed devup_screen_plan and otherwise answers plan_required; pageScaffold then takes its route from the plan. Ask the plan's questions up front only; after confirm never ask the user, record assumptions instead. Excluded and design-fix frames are refused (skill devup-implementation-plan). The `tsx` this returns is devup-ui code, not plain React: its components are compile-time placeholders, `$token` names an entry in the project's devup.json, and a style prop takes a responsive array. Call devup_skills before you write or edit it - it reports which of those conventions this workspace is missing and installs them where your runtime loads skills from. An agent that skips this does not know it is guessing, and this server cannot see the guesses; the gap is repeated as `skillGap` on the response that carries the code. This output is the design, already read. Do not rewrite it from a screenshot or from `get_design_context` - pictures and visual reasoning verify, they do not author. Do not read the node tree and write devup-ui by hand, and do not infer layout from coordinates. Never guess a colour, spacing, radius or typography value: if a value did not come back, say so and stop, because an invented one is indistinguishable from a real one in the code and is the single failure this server exists to prevent. A failed call is a fact to report, not something to route around. Ask only for what you will read: `tsx` is the deliverable, and the response always carries `status`, `quality`, `cache.artifactId`, `collection` and `source` beside it. `outputs` defaults to `["tsx"]`. Add `devupJson` only when the project has no `devup.json` yet, or when you are introducing tokens it does not define - if it already has one, that file is what the code must match, and `devup_project_context` is what reads it. If you already know the node ids you want - a brief named them, or an earlier call did - pass them straight to `frameIds` and skip `devup_figma_explore`; exploring to rediscover ids you are already holding spends a Figma call for nothing. Explore is for when a Section link is all you have. Each output adds its own keys and nothing else - tsx adds `tsx`; componentTsx adds `componentTsx`; responsiveTsx adds `responsiveTsx`, `responsiveSlots` and, where a width asked for something one tree cannot say, `responsiveUnrepresented`; devupJson adds `devupJson`, `themeCounts`, `themeCompleteness`, `conflicts` and `unresolvedVariables`; sourceMap and assetManifest each add the key they name; referencePng adds `referencePng` and, when the Devup Bridge plugin's picture may hold layers get_screenshot leaves out, `referencePngNote` naming them. `rawSnapshot` and `rawPayload` are the collected design in raw form and need `debug: true`. Use them for one question only - a screen looks wrong and you must decide whether the generator is at fault or the design says so - never to implement, since the tsx already carries what they carry. `fidelity` and `completenessReport` appear only when the result is not exact or complete, or when includeDiagnostics is set. tsx expands every instance into primitives while componentTsx keeps them as references, so requesting both gives the same screen twice and the difference between them is each component's body. responsiveTsx merges every width the capture carries into one module whose differing values are devup-ui responsive arrays, and is produced whenever there is more than one width. `assetManifest` lists the assets and their ids and writes nothing. To get files, call again with `assetRequests`, giving each entry an `outputPath` under an allowed write root - and make that call with the original `url` rather than `artifactId`, because an acquisition made without asset capture cannot serve asset requests. By default manifest `path` and TSX references remain placeholders. Opt in with `assetPublicRoot`, an existing absolute local directory served at URL /, together with assetRequests.outputPath in this call (saved output mappings are not part of artifacts): files below that root map to percent-encoded relative URLs in manifest and all TSX outputs. Identical exported bytes share one canonical path/outputPath; inspect the returned paths. assetNamesPerNode remains true by default; matching names alone never trigger deduplication. Reuse a previous acquisition with `artifactId` from `cache` to project further outputs without calling Figma again. Omitted frameIds/allScreens reuse the stored Section selection; explicit selection overrides it. Debug outputs can use resource delivery in auto mode: read the linked resources or follow nextAction to reproject inline. sourceMap is a node/field/generatedProperty/resolution map without offsets; source.generatedOutput identifies the clean output; node identities and instanceOverrides remain structured sidecars. Even when reusing artifactId, sourceMap requires tsx, componentTsx or devupJson in outputs in the same call. Example: {"artifactId":"","outputs":["tsx","rawSnapshot","sourceMap"],"debug":true} An asset request targeting a frame by nodeId defaults to the original IMAGE fill when one is available. This keeps hero headings and buttons live instead of baking them into the background image. Explicit renderMode node retains whole-node capture; its renderInfo warns when child text would be baked into the asset. diff --git a/crates/devup-mcp/src/server/text/devup-runtime-audit.md b/crates/devup-mcp/src/server/text/devup-runtime-audit.md index 27d80fcf..d77d4d5a 100644 --- a/crates/devup-mcp/src/server/text/devup-runtime-audit.md +++ b/crates/devup-mcp/src/server/text/devup-runtime-audit.md @@ -7,4 +7,7 @@ Rendered completeness requires the frame height (default minimum 90%), listed se Selection proof: expect.selected requires semantic group/target locators, attribute aria-current or aria-selected, a true selection value, and 1..12 captured CSS paint values in styles. It checks exactly one visible selected control, actual computed paint, containment and optional content visibility. Use press(target,value) and back/forward/reload(no target/value) steps to test keyboard and browser history. A URL change or stale ARIA alone never proves visual selection. Markup also detects short-page footer gaps. -Motion checks measure intermediate values for marquee, count-up, steps, tabs and reveal, with explicit candidateId and semantic selectors. A reveal check measures an entrance whatever produced it. `motion.target` is the element that carries the entrance (the inner wrapper, not the painted section) and `motion.items` names the animated children of a group. It scrolls toward the target in small steps and records `measured.trigger` and `measured.frames` (start, middle and end opacity/transform, each with a screenshot): a scroll-linked entrance (CSS `animation-timeline: view()`) must be fully shown once the block is inside the viewport or half a screen of it is showing; a timed one must start no more than 1px off screen and not after the block has been fully visible for 400ms. It then scrolls the target out of view and back: content re-hidden while away, a replay on re-entry, or a target that cannot leave the viewport at that size (re-entry unobserved) fails. Then every scenario runs from a fresh load unless `motion.scenarios` narrows the list, each reported under `measured.scenarios`: fast-scroll (fling to the bottom, then the target must be fully shown), reload and history (reload, or leave and go back, with the target on screen: it must never be hidden or displaced), bfcache (the same after a real back/forward-cache restore, in a browser started with the cache on), client-nav (follow `motion.navigate`, a link, and go back in the same document), image-delay and image-failure (images inside the target stalled or aborted: it still reveals at its reserved height), focus (a focused control inside an unrevealed target is painted, on screen and not trapped; `motion.focus` selects the control), reduced-motion (never hidden or moved while entering under prefers-reduced-motion), no-script (present and painted in the page served without JavaScript), stagger (steps between `motion.items` at most 150ms, stagger span 450ms, whole group 1000ms, or `maxStepMs`/`maxSpanMs`/`maxTotalMs`), progress-sync (with `motion.progress` and `motion.items`: each item within 200ms, or `motion.syncToleranceMs`, of the progress line reaching it). A scenario with nothing to observe in the block (no image, no control, no items) is `not-applicable`. One that could not be observed (no link named, a page the browser does not keep in bfcache, scroll not restored) is `unverified` and the check is `inconclusive`, never a pass; with an explicit `scenarios` list an unobservable scenario fails and the scenarios left out are listed in `measured.scenariosNotRun`. Ingest returns `motionEvidence`: one row per motion check per width (frames, trigger, re-entry, scenario statuses, stagger and progress timings, and what is unverified) and one line per candidate, `verified` only with a passing check at a mobile (<=767px) and a desktop (>=1024px) width and nothing left unverified. A no-clipped-content exception requires allowedMarquees naming one verified horizontal translating track; animation elsewhere never exempts a clipped container. Data-binding checks mutate only an explicitly isolated disposable SQLite database and compare baseline, changed, empty and error states across landing/list/detail. Completion independently rechecks source and artifact hashes, SQL snapshots and all required URL/width/motion/binding coverage. It always writes the canonical .devup/completion.json, optionally copying it to outputPath. Exported source alone never establishes application completion; see the completion guide for the staged contract. +Motion checks measure intermediate values for marquee, count-up, steps, tabs and reveal, with explicit candidateId and semantic selectors. A reveal check measures an entrance whatever produced it. `motion.target` is the element that carries the entrance (the inner wrapper, not the painted section) and `motion.items` names the animated children of a group. It scrolls toward the target in small steps and records `measured.trigger` and `measured.frames` (start, middle and end opacity/transform, each with a screenshot): a scroll-linked entrance (CSS `animation-timeline: view()`) must be fully shown once the block is inside the viewport or half a screen of it is showing; a timed one must start no more than 1px off screen and not after the block has been fully visible for 400ms. It then scrolls the target out of view and back: content re-hidden while away, a replay on re-entry, or a target that cannot leave the viewport at that size (re-entry unobserved) fails. Then every scenario runs from a fresh load unless `motion.scenarios` narrows the list, each reported under `measured.scenarios`: fast-scroll (sample the first on-screen frames through the settled entrance; fail if shown content subsequently disappears or moves), reload and history (reload, or leave and go back, with the target on screen: it must never be hidden or displaced), bfcache (the same after a real back/forward-cache restore, in a browser started with the cache on), client-nav (follow `motion.navigate`, a link, and go back in the same document), image-delay and image-failure (images inside the target stalled or aborted: it still reveals at its reserved height), focus (a focused control inside an unrevealed target is painted, on screen and not trapped; `motion.focus` selects the control), reduced-motion (never hidden or moved while entering under prefers-reduced-motion), no-script (present and painted in the page served without JavaScript), stagger (steps between `motion.items` at most 150ms, stagger span 450ms, whole group 1000ms, or `maxStepMs`/`maxSpanMs`/`maxTotalMs`), progress-sync (with `motion.progress` and `motion.items`: each item within 200ms, or `motion.syncToleranceMs`, of the progress line reaching it). A scenario with nothing to observe in the block (no image, no control, no items) is `not-applicable`. One that could not be observed (no link named, a page the browser does not keep in bfcache, scroll not restored) is `unverified` and the check is `inconclusive`, never a pass; with an explicit `scenarios` list an unobservable scenario fails and the scenarios left out are listed in `measured.scenariosNotRun`. Ingest returns `motionEvidence`: one row per motion check per width (frames, trigger, re-entry, scenario statuses, stagger and progress timings, and what is unverified) and one line per candidate, `verified` only with a passing check at a mobile (<=767px) and a desktop (>=1024px) width and nothing left unverified. A no-clipped-content exception requires allowedMarquees naming one verified horizontal translating track; animation elsewhere never exempts a clipped container. Data-binding checks mutate only an explicitly isolated disposable SQLite database and compare baseline, changed, empty and error states across landing/list/detail. Completion independently rechecks source and artifact hashes, SQL snapshots and all required URL/width/motion/binding coverage. It always writes the canonical .devup/completion.json, optionally copying it to outputPath. Exported source alone never establishes application completion; see the completion guide for the staged contract. + +Regression contracts run in a fresh Chromium context and are plan-bound. Use checks kind "regression" with regression.kind "sticky-header", "inquiry", "image-handoff" or "font-stability". The header checks both scroll directions, painted divider, logo/home action, default/hover/pressed link decoration and reduced motion. Inquiry checks approved description text and CTA, actual native/custom/radio selection, pressed paint, animated form validation and a mailto draft containing the selected synthetic fields. It observes the draft opening and does not send email. Image-handoff delays the next image response and its decode promise and samples visible frames. Font-stability delays explicitly listed same-origin preloads and measures first-viewport movement and CLS. The checked selectors match rendered application semantics. Item widths restrict the contract to its planned viewports. +Use a "scroll" step with a semantic locator to capture a scrolled state. For Figma sections (including a header state or a hero image), add a capture check with a native node PNG reference and the exact nodeId. Set reference.maxLuminanceDelta when a mean brightness difference matters independently of changed-pixel ratio. Bind affected route/screenId/width/nodeId combinations in completion.requiredVisualStates, and required browser contracts in completion.requiredRegressions (routePath, screenId, width, kind). A different state at the same URL and width cannot satisfy those obligations. diff --git a/crates/devup-mcp/src/server/text/devup-visual-compare.md b/crates/devup-mcp/src/server/text/devup-visual-compare.md index b61945ce..e364bed2 100644 --- a/crates/devup-mcp/src/server/text/devup-visual-compare.md +++ b/crates/devup-mcp/src/server/text/devup-visual-compare.md @@ -1,3 +1,7 @@ Compare actual PNG with one reference PNG path, cached artifactId referencePng, or {artifactId,assetId} captured native-node PNG asset. Asset comparisons validate retained reference bytes and report asset pixel scope without requiring a browser environment; raw-fill and unknown captures cannot be references. Paths must be allowlisted. Never renders or runs commands. Default threshold is 0.005. Page comparisons require a valid environment manifest for a conclusive verdict. Optional diff PNG uses auto|inline|resource delivery. Page environment.viewport records the actual CSS browser window, never the Figma frame height. environment.captureContext must carry actual innerWidth/innerHeight, devicePixelRatio, visualViewportScale and rootCssZoom/bodyCssZoom measurements. Natural full-page PNG height may differ from viewport height. This bounded schema does not prove non-unit capture/reference calibration; missing/inconsistent zoom/DPR evidence stays inconclusive. Different PNG dimensions never establish a layout error or authorize resizing/padding/cropping. +Use the top-level verdict as the result of the comparison. A successful tool call can still be inconclusive; follow nextAction and fix measured environment issues before retrying. visual.changedBounds identifies the smallest rectangle containing changed pixels. visual.meanMaxChannelDelta is the mean of each pixel's largest absolute RGBA channel difference on a 0-255 scale. Read these with the changed ratio and diff PNG: many small differences can come from rasterization, while a narrow band can point to a border. None of these changes the threshold or establishes a cause on its own. + Strict pixels also depend on font rasterization and asset encoding. Record browser launch flags with consumer evidence: identical font bounds can still have different grayscale/subpixel RGB edges. The web-ready-images preset uses lossy WebP by default; a native Figma frame PNG is not that derivative. Diagnose a suspected encoding difference with an explicit lossless original-source asset request and the same TSX, geometry and browser. Pin source/output dimensions so resizing is not confused with compression. Confirm the baseline reproduces the original screenshot and that the replacement was actually loaded; a hot-reload race or an unintercepted image invalidates the experiment. Controlled improvements identify a cause, not pixel equivalence: keep strict results and unexplained differences visible, and never move generated layout values or relax the threshold to hide them. + +For brightness, visual.meanLuminanceDelta reports the mean signed actual-minus-reference Rec. 709 channel-weighted difference for pixels opaque in both PNGs. Positive means the render is brighter. maxLuminanceDelta optionally caps its absolute value independently of the changed-pixel ratio. With no shared opaque pixels the requested brightness verdict is inconclusive. diff --git a/crates/devup-mcp/src/server/tools.rs b/crates/devup-mcp/src/server/tools.rs index f6f10088..9381088c 100644 --- a/crates/devup-mcp/src/server/tools.rs +++ b/crates/devup-mcp/src/server/tools.rs @@ -53,6 +53,10 @@ pub struct AuthInput { #[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)] #[serde(rename_all = "camelCase")] +#[schemars(extend("allOf" = serde_json::json!([{ + "if": {"required": ["outputs"], "properties": {"outputs": {"contains": {"const": "referencePng"}}}}, + "then": {"properties": {"frameIds": {"maxItems": 1}, "allScreens": {"const": false}}} +}])))] pub struct FigmaExportInput { /// Caller-declared observations from an independently inspected screenshot. /// Used only to rank actual explore candidates when selection is empty; @@ -75,6 +79,8 @@ pub struct FigmaExportInput { pub url: Option, #[serde(default)] pub artifact_id: Option, + /// Collect referencePng separately for each width using its own Figma frame + /// URL (scope=node); omit frameIds and allScreens in those calls. #[serde(default = "default_outputs")] #[schemars(extend("items" = serde_json::json!({ "type": "string", @@ -560,6 +566,10 @@ pub struct VisualCompareInput { #[serde(default)] #[schemars(range(min = 0.0, max = 1.0))] pub threshold: Option, + /// Optional maximum absolute mean signed luminance delta on shared opaque pixels (0..255). + #[serde(default)] + #[schemars(range(min = 0.0, max = 255.0))] + pub max_luminance_delta: Option, #[serde(default)] pub environment: Option, /// Include the red diff PNG using the standard binary delivery limits. diff --git a/crates/devup-mcp/src/server/visual_compare.rs b/crates/devup-mcp/src/server/visual_compare.rs index b83f968f..b45911f0 100644 --- a/crates/devup-mcp/src/server/visual_compare.rs +++ b/crates/devup-mcp/src/server/visual_compare.rs @@ -221,6 +221,9 @@ pub(super) async fn compare( if !(0.0..=1.0).contains(&options.max_changed_ratio) { return Err(invalid("threshold must be between 0 and 1 inclusive.")); } + if input.max_luminance_delta.is_some_and(|limit| !(0.0..=255.0).contains(&limit)) { + return Err(invalid("maxLuminanceDelta must be between 0 and 255 inclusive.")); + } // Resolve every supplied path before any PNG read. let actual_target = policy.resolve(&input.actual)?; let reference_target = match &input.reference { @@ -370,9 +373,14 @@ pub(super) async fn compare( environment["filledByServer"] = json!(filled); } let passed = report.passed(); - let verdict = if environment["status"] != "valid" { + let luminance = input.max_luminance_delta.map(|limit| { + let measured = report.mean_luminance_delta; + json!({"limit":limit,"actualMinusReference":measured,"passed":measured.map(|value| value.abs() <= limit)}) + }); + let verdict = if environment["status"] != "valid" + || luminance.as_ref().is_some_and(|check| check["passed"].is_null()) { "inconclusive" - } else if passed { + } else if passed && luminance.as_ref().is_none_or(|check| check["passed"] == true) { "pass" } else { "fail" @@ -382,6 +390,9 @@ pub(super) async fn compare( visual["passed"] = json!(passed); let mut result = json!({"verdict":verdict,"visual":visual,"environment":environment,"reference":provenance}); + if let Some(luminance) = luminance { + result["luminance"] = luminance; + } result["comparisonScope"] = json!(if asset_comparison { "asset-pixels-against-native-node-export" } else { @@ -400,6 +411,12 @@ pub(super) async fn compare( }); if asset_comparison { result["canvasFidelity"] = json!("unverified-outside-reference-node-subtree"); + } else if result["environment"]["status"] != "valid" { + result["nextAction"] = json!({ + "kind": "repair-capture-environment", + "guide": "devup://guide/usage", + "how": "Resolve environment.issues using measured browser evidence, then rerun this comparison. For a source-bound application audit, use devup_runtime_audit plan and ingest with Figma references and visualEnvironments." + }); } if let (Some(target), Some(bytes)) = (diff_target, diff.as_ref()) { let display = target.display_path().display().to_string(); diff --git a/crates/devup-mcp/src/server/visual_compare_tests.rs b/crates/devup-mcp/src/server/visual_compare_tests.rs index 9b08c316..835995f8 100644 --- a/crates/devup-mcp/src/server/visual_compare_tests.rs +++ b/crates/devup-mcp/src/server/visual_compare_tests.rs @@ -83,10 +83,30 @@ async fn missing_environment_inconclusive() { let f = fixture(); let mut i = input(); i.as_object_mut().unwrap().remove("environment"); + f.png("actual.png", BLACK); let r = run(i, &f.policy(), &ArtifactStore::default()) .await .unwrap(); assert_eq!(r["verdict"], "inconclusive"); + assert_eq!(r["visual"]["status"], "mismatch"); + assert_eq!(r["visual"]["changedBounds"], json!({"x":0,"y":0,"width":1,"height":1})); + assert_eq!(r["visual"]["meanMaxChannelDelta"], 255.0); + assert_eq!(r["nextAction"]["kind"], "repair-capture-environment"); +} + +#[tokio::test] +async fn hero_brightness_can_fail_a_comparison_below_the_changed_pixel_limit() { + let f = fixture(); + f.png("reference.png", BLACK); + let mut args = input(); + args["environment"]["referenceResource"]["sha256"] = json!(hash(&STANDARD.decode(BLACK).unwrap())); + args["threshold"] = json!(1.0); + args["maxLuminanceDelta"] = json!(5.0); + let result = run(args, &f.policy(), &ArtifactStore::default()).await.unwrap(); + assert_eq!(result["visual"]["passed"], true); + assert_eq!(result["luminance"]["actualMinusReference"], 255.0); + assert_eq!(result["luminance"]["passed"], false); + assert_eq!(result["verdict"], "fail"); } async fn asset_store(representation: &str, broken_hash: bool) -> (ArtifactStore, String) { diff --git a/crates/devup-mcp/tests/runtime_audit_tool.rs b/crates/devup-mcp/tests/runtime_audit_tool.rs index 8525d025..0b9bc63b 100644 --- a/crates/devup-mcp/tests/runtime_audit_tool.rs +++ b/crates/devup-mcp/tests/runtime_audit_tool.rs @@ -176,7 +176,7 @@ async fn consumer_template_is_allowlisted_and_missing_acquisitions_never_pass() assert!(!failed, "{planned}"); assert_eq!(planned["template"]["executed"], false); assert_eq!(planned["dimensionReferences"][0]["status"], "unverified"); - assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 15); + assert_eq!(planned["template"]["files"].as_array().unwrap().len(), 16); let markup = std::fs::read_to_string(root.join("consumer-audit/markup-checks.mjs"))?; assert!(markup.contains("collectMarkup")); let runner = std::fs::read_to_string(root.join("consumer-audit/run.mjs"))?; diff --git a/harness/runtime-audit/fixtures/regression-wide.ttf b/harness/runtime-audit/fixtures/regression-wide.ttf new file mode 100644 index 00000000..745dbc33 Binary files /dev/null and b/harness/runtime-audit/fixtures/regression-wide.ttf differ diff --git a/harness/runtime-audit/regression-checks.mjs b/harness/runtime-audit/regression-checks.mjs new file mode 100644 index 00000000..8d4b9280 --- /dev/null +++ b/harness/runtime-audit/regression-checks.mjs @@ -0,0 +1,408 @@ +// These contracts run in a fresh context, without frozen animations or shared +// route state. The parent installs its usual origin guard before navigation. +const PAINT = ['backgroundColor', 'color', 'opacity', 'transform', 'boxShadow', 'outlineColor', 'outlineWidth', 'borderColor']; +const TRANSPARENT = 'rgba(0, 0, 0, 0)'; +const HELP = new Map([ + ['sticky-header', 'Sticky header state, motion and home action'], + ['inquiry', 'Detail and inquiry form flow'], + ['image-handoff', 'Artwork image handoff'], + ['font-stability', 'First-viewport font stability'], +]); + +async function one(page, selector) { + const locator = page.locator(selector); + await locator.waitFor({ state: 'visible' }).catch(() => { + throw new Error('Element did not become visible: ' + selector); + }); + if (await locator.count() !== 1) throw new Error('Expected one visible element: ' + selector); + return locator; +} + +const paint = locator => locator.evaluate((element, fields) => { + const style = getComputedStyle(element); + return fields.map(field => style[field]); +}, PAINT); + +async function pressed(page, locator) { + const touch = await page.evaluate(() => navigator.maxTouchPoints > 0); + if (touch) await locator.click({ trial: true }); + else await locator.hover(); + await page.waitForTimeout(150); + const before = await paint(locator); + const session = touch ? await page.context().newCDPSession(page) : null; + try { + if (session) { + const box = await locator.boundingBox(); + await session.send('Input.dispatchTouchEvent', { + type: 'touchStart', touchPoints: [{ x: Math.floor(box.x + box.width / 2), y: Math.floor(box.y + box.height / 2) }], + }); + } else { + await page.mouse.down(); + } + let changed = false; + let underlineFree = true; + for (let sample = 0; sample < 10; sample++) { + await page.evaluate(() => new Promise(requestAnimationFrame)); + const after = await paint(locator); + changed ||= before.some((value, index) => value !== after[index]); + underlineFree &&= await decoration(locator); + } + return { changed, decoration: underlineFree }; + } finally { + if (session) { + await session.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] }).catch(() => {}); + await session.detach().catch(() => {}); + } else { + await page.mouse.move(-1, -1); + await page.mouse.up(); + } + } +} + +const decoration = locator => locator.evaluate(element => ![element, ...element.querySelectorAll('*')] + .some(node => getComputedStyle(node).textDecorationLine.includes('underline'))); + +async function stickyHeader(page, config) { + const { header, hero, logo, links, scrolledBackground } = config; + const nav = await one(page, header); + const atTop = await nav.evaluate(element => { + const box = element.getBoundingClientRect(); + return { height: box.height, top: box.top }; + }); + const logoAtTop = await page.locator(logo).evaluate(el => { + const box = el.getBoundingClientRect(); + return el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) && + box.x >= 0 && box.y >= 0 && box.right <= innerWidth && box.bottom <= innerHeight; + }).catch(() => false); + const sample = async (down, reduced) => nav.evaluate(async (element, options) => { + const { down, hero, reduced } = options; + const next = down ? document.querySelector(hero).getBoundingClientRect().bottom + scrollY : 0; + const top = element.getBoundingClientRect().top; + const height = element.getBoundingClientRect().height; + const read = () => { + const paints = [null, '::before', '::after'].map(pseudo => getComputedStyle(element, pseudo)) + .filter((style, index) => index === 0 || !['none', 'normal'].includes(style.content)); + const root = paints[0]; + const divider = paints.some(style => { + const shadow = style.boxShadow.replace(/rgba?\([^)]*\)/g, ''); + return (parseFloat(style.borderBottomWidth) > 0 && style.borderBottomStyle !== 'none' && + style.borderBottomColor !== 'rgba(0, 0, 0, 0)') || + /(?:^|,)\s*0px -[\d.]+px [^,]*\binset\b/.test(shadow) || + (style.position === 'absolute' && style.bottom === '0px' && parseFloat(style.height) <= 2 && + parseFloat(style.height) > 0 && style.backgroundColor !== 'rgba(0, 0, 0, 0)'); + }); + return { background: root.backgroundColor, divider }; + }; + const start = read(); + scrollTo({ top: next, behavior: 'instant' }); + const colors = new Set(); + const startTime = performance.now(); + let stable = true; + let transitioned = false; + while (performance.now() - startTime < (reduced ? 150 : 500)) { + await new Promise(requestAnimationFrame); + colors.add(read().background); + const box = element.getBoundingClientRect(); + stable &&= Math.abs(box.top - top) < 1 && Math.abs(box.height - height) < 1; + transitioned ||= element.getAnimations().some(animation => animation.transitionProperty === 'background-color'); + } + const end = read(); + return { + start, end, stable, transitioned, + intermediate: [...colors].filter(value => value !== start.background && value !== end.background).length, + y: scrollY, + }; + }, { hero, down, reduced }); + + const down = await sample(true, false); + const up = await sample(false, false); + const linkDecorations = async () => { + const current = page.locator(links); + const count = await current.count(); + if (count > 16) throw new Error('Sticky header contract accepts at most 16 links.'); + const states = []; + for (let index = 0; index < count; index++) { + const link = current.nth(index); + if (!(await link.isVisible())) continue; + await page.mouse.move(-1, -1); + const resting = await decoration(link); + await link.hover(); + await page.waitForTimeout(150); + const hovered = await decoration(link); + const active = await pressed(page, link); + states.push({ resting, hovered, pressed: active.decoration }); + } + return states; + }; + const heroLinks = await linkDecorations(); + await page.emulateMedia({ reducedMotion: 'reduce' }); + const reduced = await sample(true, true); + const scrolledLinks = await linkDecorations(); + const linkStates = { hero: heroLinks, scrolled: scrolledLinks }; + const scrolledLogo = await one(page, logo); + const homePath = new URL(page.url()).pathname; + const homeHref = await scrolledLogo.evaluate(el => el instanceof HTMLAnchorElement && new URL(el.href).origin === location.origin && + new URL(el.href).pathname === location.pathname && !new URL(el.href).hash); + if (homeHref) await scrolledLogo.click(); + const returnedHome = homeHref && await page.waitForFunction(path => scrollY < 5 && location.pathname === path && !location.hash, homePath, { timeout: 1500 }) + .then(() => true, () => false); + const issues = []; + if (!logoAtTop || !returnedHome) issues.push('Logo must be visible on the hero and return to the top from the scrolled state.'); + if (down.start.background !== TRANSPARENT || up.end.background !== TRANSPARENT || down.start.divider || up.end.divider) { + issues.push('The hero state must be transparent and have no divider.'); + } + if (down.end.background !== scrolledBackground || !down.end.divider) issues.push('Scrolled background or divider differs from the approved state.'); + if (down.y < 5 || !down.stable || !up.stable || atTop.top > 1) issues.push('The header must stay in place while scrolling.'); + if (!(down.intermediate > 0 && up.intermediate > 0 && down.transitioned && up.transitioned)) issues.push('Background must interpolate in both directions.'); + if (reduced.transitioned || reduced.intermediate !== 0 || reduced.end.background !== scrolledBackground) issues.push('Reduced motion must apply the scrolled endpoint immediately.'); + if (Object.values(linkStates).some(links => !links.length || links.some(state => !state.resting || !state.hovered || !state.pressed))) { + issues.push('Navigation links show underlines in a tested state, or no links were measured.'); + } + return { issues, measured: { logoAtTop, homeHref, returnedHome, down, up, reduced, linkStates } }; +} + +async function inquiry(page, config) { + await (await one(page, config.open)).click(); + await one(page, config.detail); + const description = await one(page, config.description); + const descriptionMatches = (await description.innerText()).replace(/\s+/g, ' ').trim() === config.descriptionText.replace(/\s+/g, ' ').trim(); + await (await one(page, config.inquire)).click(); + await one(page, config.form); + const submit = await one(page, config.submit); + const session = await page.context().newCDPSession(page); + const drafts = []; + const record = event => { if (event.url.startsWith('mailto:')) drafts.push(new URL(event.url)); }; + await session.send('Page.enable'); + session.on('Page.frameRequestedNavigation', record); + try { + await submit.click(); + const shownError = await one(page, config.error); + const validationMotion = await shownError.evaluate(el => el.getAnimations({ subtree: true }).length > 0); + const rejectedEmpty = drafts.length === 0; + const choice = await one(page, config.choice.control); + const press = await pressed(page, choice); + const selectedTarget = config.choice.selected ? page.locator(config.choice.selected) : null; + const matchesSelection = () => selectedTarget.evaluate((element, value) => + element instanceof HTMLInputElement ? element.checked && element.value === value : element.textContent.trim() === value, config.choice.value); + let selected; + let initiallySelected; + if (config.choice.selected) { + initiallySelected = await selectedTarget.count() === 1 && await matchesSelection(); + await choice.click(); + if (config.choice.option) await (await one(page, config.choice.option)).click(); + selected = await matchesSelection(); + } else { + initiallySelected = (await choice.inputValue()) === config.choice.value; + await choice.selectOption(config.choice.value); + selected = (await choice.inputValue()) === config.choice.value; + } + for (const field of config.fields) await (await one(page, field.selector)).fill(field.value); + await submit.click(); + for (let attempt = 0; attempt < 12 && drafts.length === 0; attempt++) await page.waitForTimeout(50); + const draft = drafts.at(-1); + const body = draft?.searchParams.get('body') ?? ''; + const subject = draft?.searchParams.get('subject') ?? ''; + const carriesFields = config.fields.every(({value}) => body.includes(value)) && + (subject.includes(config.choice.value) || body.includes(config.choice.value)); + const recipientMatches = Boolean(draft) && decodeURIComponent(draft.pathname) === config.recipient; + const measured = { descriptionMatches, rejectedEmpty, validationMotion, pressed: press.changed, selected: !initiallySelected && selected, carriesFields, recipientMatches }; + const reasons = { + descriptionMatches: 'Artwork description differs from the approved copy.', + rejectedEmpty: 'Empty submission opened an email draft.', + validationMotion: 'Required-field feedback did not animate.', + pressed: 'The inquiry type control has no measured pressed state.', + selected: 'The expected inquiry type was not selected.', + carriesFields: 'The draft is missing the selected inquiry type or field values.', + recipientMatches: 'Submission did not open the expected mailto draft.', + }; + const issues = Object.entries(measured).filter(([, pass]) => !pass).map(([key]) => reasons[key]); + return { issues, measured }; + } finally { + await session.detach().catch(() => {}); + } +} + +function holdResources(page, urlList) { + const urls = new Set(urlList); + const started = new Set(); + const succeeded = new Set(); + let release; + const held = new Promise(resolve => { release = resolve; }); + const route = page.route(url => urls.has(url.href), async request => { + started.add(request.request().url()); + await held; + await request.fallback(); + }); + page.on('response', response => { + if (urls.has(response.url()) && response.ok()) succeeded.add(response.url()); + }); + return { route, started, succeeded, release }; +} + +const matchesReadyImage = ({ images, nextSrc }) => [...document.querySelectorAll(images)].some(img => + img instanceof HTMLImageElement && img.currentSrc === nextSrc && img.complete && img.naturalWidth > 0 && + img.checkVisibility({ opacityProperty: true, visibilityProperty: true })); + +async function swipeArtwork(page, target, direction) { + await target.scrollIntoViewIfNeeded(); + const box = await target.boundingBox(); + const x = Math.floor(box.x + box.width / 2); + const y = Math.floor(box.y + box.height / 2); + const end = x + (direction === 'left' ? -1 : 1) * Math.min(Math.floor(box.width / 3), 100); + const session = await page.context().newCDPSession(page); + try { + await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + await session.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x: end, y }] }); + await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); + } finally { + await session.detach().catch(() => {}); + } +} + +async function imageHandoff(page, config, url) { + const nextSrc = new URL(config.nextSrc, url).href; + const held = holdResources(page, [nextSrc]); + await held.route; + try { + await page.addInitScript(expected => { + const decode = HTMLImageElement.prototype.decode; + let release; + const ready = new Promise(resolve => { release = resolve; }); + const gate = { observed: false, release }; + window.__devupDecodeGate = gate; + HTMLImageElement.prototype.decode = function () { + const decoded = decode.call(this); + if ((this.currentSrc || this.src) !== expected) return decoded; + gate.observed = true; + return Promise.all([decoded, ready]).then(() => undefined); + }; + }, nextSrc); + await page.goto(url, { waitUntil: 'domcontentloaded' }); + if (config.ready) await page.locator(config.ready).waitFor({ state: 'attached' }); + else await page.waitForLoadState('load', { timeout: 1000 }).catch(() => {}); + if (config.open) await (await one(page, config.open)).click(); + await page.waitForFunction(images => [...document.querySelectorAll(images)].some(img => img.complete && img.naturalWidth > 0 && + img.checkVisibility({ opacityProperty: true, visibilityProperty: true })), config.images) + .catch(() => { throw new Error("The starting artwork was not visibly loaded."); }); + const start = await page.evaluate(images => [...document.querySelectorAll(images)] + .find(img => img.complete && img.naturalWidth > 0 && img.checkVisibility({ opacityProperty: true, visibilityProperty: true })).currentSrc, config.images); + if (start === nextSrc) throw new Error('The starting image already uses nextSrc.'); + await page.evaluate(images => { + const audit = { samples: 0, blankFrames: 0, running: true }; + window.__devupImageAudit = audit; + const sample = () => { + if (!audit.running) return; + audit.samples++; + if (![...document.querySelectorAll(images)].some(img => { + if (!(img instanceof HTMLImageElement && img.complete && img.naturalWidth > 0 && + img.checkVisibility({ opacityProperty: true, visibilityProperty: true }))) return false; + const box = img.getBoundingClientRect(); + return box.bottom > 0 && box.top < innerHeight && box.right > 0 && box.left < innerWidth; + })) audit.blankFrames++; + requestAnimationFrame(sample); + }; + requestAnimationFrame(sample); + }, config.images); + if (config.swipe) await swipeArtwork(page, await one(page, config.images), config.swipe); + else await (await one(page, config.next)).click(); + await page.waitForTimeout(300); + const heldRequest = held.started.has(nextSrc); + held.release(); + await page.waitForFunction(() => window.__devupDecodeGate.observed, null, { timeout: 650 }).catch(() => {}); + const released = await page.evaluate(config => { + const gate = window.__devupDecodeGate; + const visibleBeforeDecode = [...document.querySelectorAll(config.images)].some(img => + img.currentSrc === config.nextSrc && img.checkVisibility({ opacityProperty: true, visibilityProperty: true })); + gate.release(); + return { observedDecode: gate.observed, visibleBeforeDecode }; + }, { images: config.images, nextSrc }); + await page.waitForFunction(matchesReadyImage, { images: config.images, nextSrc }) + .catch(() => { throw new Error("The expected replacement artwork did not become visible."); }); + const decoded = await page.locator(config.images).evaluateAll(async (images, src) => { + const img = images.find(image => image.currentSrc === src); + return img?.decode().then(() => true, () => false) ?? false; + }, nextSrc); + await page.waitForTimeout(250); + const { samples, blankFrames } = await page.evaluate(() => { + window.__devupImageAudit.running = false; + return window.__devupImageAudit; + }); + const issues = []; + if (!heldRequest) issues.push('The next-image response was not held during the handoff.'); + if (samples < 2 || blankFrames > 0) issues.push('At least one handoff frame lacked a painted artwork image, or frames were not observed.'); + if (!released.observedDecode || released.visibleBeforeDecode) issues.push('The replacement became visible without a measured decode wait.'); + if (!decoded || !held.succeeded.has(nextSrc)) issues.push('The expected replacement image did not load and decode.'); + return { issues, measured: { heldRequest, decoded, samples, blankFrames, ...released } }; + } finally { + held.release(); + } +} + +const positions = (page, selectors) => page.evaluate(selectors => selectors.map(selector => { + const nodes = [...document.querySelectorAll(selector)]; + if (nodes.length !== 1) throw new Error('Font stability target needs exactly one element: ' + selector); + const { x, y, width, height } = nodes[0].getBoundingClientRect(); + if (!width || !height || y >= innerHeight || y + height <= 0) throw new Error('Font stability target is outside the first viewport: ' + selector); + return { x, y }; +}), selectors); + +async function fontStability(page, config, url) { + const fonts = config.fonts.map(path => new URL(path, url).href); + const held = holdResources(page, fonts); + await held.route; + try { + await page.addInitScript(() => { + window.__devupFontShifts = []; + if (!PerformanceObserver.supportedEntryTypes.includes('layout-shift')) return; + new PerformanceObserver(list => { + for (const entry of list.getEntries()) { + if (!entry.hadRecentInput) window.__devupFontShifts.push(entry.value); + } + }).observe({ type: 'layout-shift', buffered: true }); + }); + await page.goto(url, { waitUntil: 'domcontentloaded' }); + for (const selector of config.targets) await one(page, selector); + await page.waitForFunction(() => performance.now() >= 1500 && + performance.getEntriesByName('first-contentful-paint').length > 0, null, { timeout: 5000 }); + const before = await positions(page, config.targets); + const started = fonts.every(font => held.started.has(font)); + const preloaded = await page.evaluate(fonts => { + const hrefs = [...document.querySelectorAll('link[rel="preload"][as="font"]')] + .filter(link => !link.media || matchMedia(link.media).matches).map(link => link.href); + return fonts.every(font => hrefs.includes(font)); + }, fonts); + held.release(); + await page.waitForLoadState('load'); + await page.evaluate(() => document.fonts.ready); + await page.waitForTimeout(100); + const after = await positions(page, config.targets); + const maxMove = Math.max(...after.map((box, index) => Math.hypot(box.x - before[index].x, box.y - before[index].y))); + const cls = await page.evaluate(() => PerformanceObserver.supportedEntryTypes.includes('layout-shift') + ? window.__devupFontShifts.reduce((sum, value) => sum + value, 0) : null); + const loaded = fonts.every(font => held.succeeded.has(font)); + const issues = []; + if (!started || !preloaded || !loaded) issues.push('Expected first-viewport font was not preloaded and fetched.'); + if (maxMove > 0.5 || cls === null || cls > 0.001) issues.push('First-viewport layout shifted while fonts loaded, or CLS was not observed.'); + return { issues, measured: { preloaded, loaded, started, maxMove, cls } }; + } finally { + held.release(); + } +} + +export async function runRegressionCheck(page, config, url) { + try { + let result; + if (config.kind === 'image-handoff') result = await imageHandoff(page, config, url); + else if (config.kind === 'font-stability') result = await fontStability(page, config, url); + else if (config.kind === 'sticky-header' || config.kind === 'inquiry') { + await page.goto(url, { waitUntil: 'load' }); + await page.evaluate(() => document.fonts.ready); + result = await (config.kind === 'sticky-header' ? stickyHeader : inquiry)(page, config); + } else { + return { status: 'inconclusive', reason: 'Unknown browser regression contract.', measured: {} }; + } + return { status: result.issues.length ? 'fail' : 'pass', reason: result.issues.join(' ') || HELP.get(config.kind), measured: result.measured }; + } catch (error) { + return { status: 'fail', reason: String(error.message ?? error).split('\n')[0], measured: {} }; + } +} diff --git a/harness/runtime-audit/reveal-checks.mjs b/harness/runtime-audit/reveal-checks.mjs index 5a916dde..49d11908 100644 --- a/harness/runtime-audit/reveal-checks.mjs +++ b/harness/runtime-audit/reveal-checks.mjs @@ -115,6 +115,38 @@ function installRevealLibrary() { return { verified: true, mode, startedOffscreen: false, late: true, visibleRatio: ratio(node), start: first, middle, end: sample(node, items) }; }; + // Start observing before scrolling so a painted resting frame cannot + // disappear into an entrance while the audit waits for the animation. + const enter = async (node, items, ms) => { + const list = parts(node, items); + const firstShown = new Map(); + let flash = null, visibleFrames = 0; + const capture = () => { + let visible = false; + for (const [index, part] of list.entries()) { + const box = part.getBoundingClientRect(); + if (box.bottom <= 0 || box.top >= innerHeight || box.right <= 0 || box.left >= innerWidth) continue; + visible = true; + const opacity = getComputedStyle(part).visibility === 'visible' ? paintedOpacity(part, node) : 0; + const current = { opacity, translate: Math.abs(shiftOf(part)), scrollY }; + if (current.opacity >= 0.99 && current.translate <= 0.1) { + if (!firstShown.has(index)) firstShown.set(index, current); + } else if (!flash && firstShown.has(index) && (current.opacity < 0.95 || current.translate > 1)) { + flash = { itemIndex: index, before: firstShown.get(index), after: current }; + } + } + if (visible) visibleFrames++; + }; + capture(); + node.scrollIntoView({ block: 'center', behavior: 'instant' }); + const end = performance.now() + ms; + while (performance.now() < end) { + await frame(); + capture(); + } + return { visibleFrames, flash, sample: sample(node, items) }; + }; + // Watches the target for a while and reports whether it was ever hidden or // displaced while on screen. const watch = async (node, items, ms) => { @@ -153,7 +185,7 @@ function installRevealLibrary() { return { verified: true, scrollLinked, observed: hiddenOnce.filter(Boolean).length, startedAt, shownAt }; }; - window.__devupReveal = { frame, sample, shown, intermediate, approach, watch, timeItems }; + window.__devupReveal = { frame, sample, shown, intermediate, approach, enter, watch, timeItems }; } const shown = value => value.opacity === 1 && Math.abs(value.translate) < 0.1; @@ -269,9 +301,13 @@ export async function runRevealCheck(page, options, measured, context = {}) { try { if (name === 'fast-scroll') { await fresh(); - await page.evaluate(async () => { for (let index = 0; index < 400 && scrollY < document.documentElement.scrollHeight - innerHeight - 1; index++) { scrollBy(0, innerHeight * 1.5); await new Promise(resolve => requestAnimationFrame(resolve)); } }); - await center(page); await page.waitForTimeout(ms + 150 + (items ? options.maxTotalMs ?? 1000 : 0)); - const value = await sampleOn(page); result = { status: shown(value) ? 'pass' : 'fail', sample: value }; + const observed = await target.evaluate((node, config) => window.__devupReveal.enter(node, config.items, config.ms), + { items, ms: ms + 400 + (items ? options.maxTotalMs ?? 1000 : 0) }); + if (observed.visibleFrames < 2) result = unverified('fewer than two on-screen frames were available'); + else { + result = { ...observed, status: !observed.flash && shown(observed.sample) ? 'pass' : 'fail' }; + if (observed.flash) result.reason = 'An on-screen item was shown before the entrance hid or displaced it.'; + } } else if (name === 'reload' || name === 'history') { await fresh(); await center(page); await page.waitForTimeout(ms + 150 + (items ? options.maxTotalMs ?? 1000 : 0)); if (name === 'reload') await page.reload({ waitUntil: 'load' }); diff --git a/harness/runtime-audit/run.mjs b/harness/runtime-audit/run.mjs index 2efca212..463e6e73 100644 --- a/harness/runtime-audit/run.mjs +++ b/harness/runtime-audit/run.mjs @@ -19,6 +19,7 @@ import { invalidateReloadedScreen, observeDevServer, serverLogReader } from './d import { collectMarkup, evaluateMarkup } from './markup-checks.mjs'; import { assertSelection } from './selection-checks.mjs'; import { installMotionProbe, runMotionCheck } from './motion-checks.mjs'; +import { runRegressionCheck } from './regression-checks.mjs'; import { runDataBindingCheck } from './data-checks.mjs'; import { sourceDigest } from './source-digest.mjs'; import { evaluateInputFocus, observeInputFocus } from './input-focus-checks.mjs'; @@ -892,6 +893,10 @@ async function runViewport(browser, plan, viewport, out, deadline, references, r if (step.action === 'click') await target.click({ timeout }); else if (step.action === 'press') await target.press(step.value, { timeout }); else if (step.action === 'fill') await target.fill(step.value, { timeout }); + else if (step.action === 'scroll') { + await target.waitFor({ state: 'visible', timeout }); + await target.evaluate(element => element.scrollIntoView({ block: 'start', behavior: 'instant' })); + } else throw new Error(`unknown step action: ${step.action}`); } } @@ -937,6 +942,21 @@ async function runViewport(browser, plan, viewport, out, deadline, references, r record.checks.push({ ...item, ...await runDataBindingCheck(check, page, { out, viewport, ...auditBinding }) }); continue; } + if (check.kind === 'regression') { + const fresh = await browser.newContext(contextOptions); + try { + await guardOrigins(fresh, allowed, blocked); + const tab = await fresh.newPage(); + tab.setDefaultTimeout(stepTimeout); + tab.setDefaultNavigationTimeout(stepTimeout); + const url = new URL(screen.routePath ?? page.url(), plan.baseUrl); + if (!allowed.has(url.origin)) throw new Error('Regression URL is outside allowedOrigins.'); + record.checks.push({ ...item, ...await runRegressionCheck(tab, check.regression, url.href) }); + } finally { + await fresh.close(); + } + continue; + } if (check.kind === 'motion') { await restoreAnimations(page); // Start, middle and end frames of an entrance are kept as evidence. diff --git a/harness/runtime-audit/test/regression.test.mjs b/harness/runtime-audit/test/regression.test.mjs new file mode 100644 index 00000000..1cc8afd6 --- /dev/null +++ b/harness/runtime-audit/test/regression.test.mjs @@ -0,0 +1,168 @@ +import assert from 'node:assert/strict'; +import { createServer } from 'node:http'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import test from 'node:test'; +import { chromium } from 'playwright'; +import { runRegressionCheck } from '../regression-checks.mjs'; +import { runPlan } from '../run.mjs'; + +const title = 'A hand-thrown bowl with a brushed glaze.'; +const contracts = { + header: { kind: 'sticky-header', header: 'nav', hero: '#hero', logo: '#logo', links: 'nav a', scrolledBackground: 'rgb(246, 245, 243)' }, + inquiry: { + kind: 'inquiry', open: '#open', detail: 'dialog[open]', description: 'dialog p', + descriptionText: title, inquire: '#inquire', form: 'form', + choice: { control: 'label[for=order]', selected: '#order', value: 'Commission' }, + fields: [{ selector: '#name', value: 'Test visitor' }, { selector: '#message', value: 'About the bowl' }], + error: '#error', submit: '#send', recipient: 'fixture@example.test', + }, + image: { kind: 'image-handoff', open: '#open', images: 'dialog img', next: '#next', nextSrc: '/second.svg' }, + font: { kind: 'font-stability', fonts: ['/wide.ttf'], targets: ['#label', '#menu'] }, +}; + +function header(mode) { + return `
+ `; +} + +function inquiry(mode) { + return `

${mode === 'description' ? 'Wrong description' : title}

+ ${mode === 'cta' ? '' : ''}
+ + `; +} + +function image(mode) { + return ` + `; +} + +function font(mode) { + return `${mode === 'preload' ? '' : ''} +
MMMMContact
`; +} + +test('UI regression contracts distinguish approved behavior from broken implementations', { timeout: 120000 }, async () => { + const face = await readFile(new URL('../fixtures/regression-wide.ttf', import.meta.url)); + const fixtures = { header, inquiry, image, font }; + const server = createServer((request, response) => { + const url = new URL(request.url, 'http://127.0.0.1'); + if (url.pathname === '/wide.ttf') { + response.writeHead(200, { 'content-type': 'font/ttf' }).end(face); + } else if (['/first.svg', '/second.svg'].includes(url.pathname)) { + const color = url.pathname === '/first.svg' ? 'red' : 'blue'; + response.writeHead(200, { 'content-type': 'image/svg+xml' }).end(``); + } else { + const name = url.searchParams.get('check'); + const render = fixtures[name]; + response.writeHead(render ? 200 : 404, { 'content-type': 'text/html' }).end(render ? '' + render(url.searchParams.get('mode')) : 'missing fixture'); + } + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const browser = await chromium.launch(); + try { + async function check(name, mode, width) { + const swipe = name === 'image' && width === 360; + const page = await browser.newPage({ viewport: { width, height: 740 }, hasTouch: swipe, isMobile: swipe }); + const contract = swipe ? { ...contracts[name], next: undefined, swipe: 'left' } : contracts[name]; + page.setDefaultTimeout(2000); + try { + return await runRegressionCheck(page, contract, `http://127.0.0.1:${server.address().port}/?check=${name}&mode=${mode}`); + } finally { + await page.close(); + } + } + for (const width of [360, 1440]) { + for (const name of Object.keys(contracts)) { + const result = await check(name, 'good', width); + assert.equal(result.status, 'pass', JSON.stringify({ name, width, result })); + } + } + for (const [name, mode, reason] of [ + ['header', 'logo', /Logo/], ['header', 'home', /return to the top/], + ['header', 'line', /no divider/], ['header', 'snap', /interpolate/], + ['header', 'underline', /underlines/], ['inquiry', 'description', /description differs/], + ['inquiry', 'cta', /#inquire/], ['inquiry', 'select', /was not selected/], + ['inquiry', 'pressed', /pressed state/], ['inquiry', 'error-motion', /did not animate/], + ['image', 'white', /lacked a painted artwork image/], ['font', 'preload', /not preloaded/], + ['font', 'shift', /layout shifted/], + ]) { + const result = await check(name, mode, 360); + assert.equal(result.status, 'fail', JSON.stringify({ name, mode, result })); + assert.match(result.reason, reason, JSON.stringify({ name, mode, result })); + } + const dir = await mkdtemp(join(tmpdir(), 'devup-regression-plan-')); + try { + const baseUrl = 'http://127.0.0.1:' + server.address().port; + const plan = join(dir, 'plan.json'); + await writeFile(plan, JSON.stringify({ + schemaVersion: 1, kind: 'devup-runtime-audit-plan', planId: 'sticky-regression', + plan: { + baseUrl, allowedOrigins: [baseUrl], + viewports: [{ width: 360, height: 740 }], + screens: ['good', 'line'].map(mode => ({ + id: mode, routePath: '/?check=header&mode=' + mode, + checks: [{ kind: 'regression', regression: contracts.header }], + })), + }, + })); + const report = await runPlan({ plan, out: join(dir, 'out'), maxMinutes: 1 }); + const [good, line] = report.runs[0].screens.map(screen => screen.checks[0]); + assert.equal(good.status, 'pass', JSON.stringify(good)); + assert.equal(line.status, 'fail', JSON.stringify(line)); + assert.match(line.reason, /no divider/); + } finally { + await rm(dir, { recursive: true, force: true }); + } + } finally { + await browser.close(); + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/harness/runtime-audit/test/reveal.test.mjs b/harness/runtime-audit/test/reveal.test.mjs index 96ad34d9..6e2ecf99 100644 --- a/harness/runtime-audit/test/reveal.test.mjs +++ b/harness/runtime-audit/test/reveal.test.mjs @@ -22,6 +22,7 @@ ${mode==='markup-hidden'?'':''}${spacer}< const mode=${JSON.stringify(mode)},node=document.querySelector('#reveal');let played=false,first=true; node.removeAttribute('data-hidden'); const reduce=matchMedia('(prefers-reduced-motion: reduce)').matches&&mode!=='ignores-preference'; +if(mode==='good' && node.getBoundingClientRect().top>=innerHeight && !reduce) node.style.opacity='0'; const play=()=>node.animate([{opacity:0,transform:'translateY(24px)'},{opacity:1,transform:'translateY(0)'}],{duration:300,easing:'linear'}); if(mode==='image-gated'){node.style.opacity='0';node.querySelector('img').addEventListener('load',()=>{node.style.opacity='';});} if(mode==='pageshow-replay')addEventListener('pageshow',event=>{if(event.persisted)play();}); @@ -34,6 +35,8 @@ else new IntersectionObserver(entries=>entries.forEach(entry=> { if(!entry.isIntersecting||played)return;played=true; if(mode==='stuck'){node.style.opacity='0';return;} if(mode==='late'){setTimeout(play,900);return;} + if(mode==='entry-flash'){setTimeout(play,120);return;} + if(mode==='good')node.style.opacity=''; if(initial&&mode!=='flash')return; if(reduce)return; if(node.contains(document.activeElement)&&mode!=='focusanim')return; @@ -201,6 +204,21 @@ test('each fresh-load scenario fails the page that breaks its rule', {timeout:60 }); }); +test('fast entry rejects a visible resting frame followed by a fade from below', {timeout:60000}, async()=> { + await withPages(async check=> { + for(const viewport of VIEWPORTS) { + const result=await check('mode=entry-flash',{scenarios:['fast-scroll']},viewport); + const entry=result.measured.scenarios['fast-scroll']; + assert.equal(result.status,'fail',JSON.stringify(result)); + assert.equal(entry.status,'fail'); + assert.ok(entry.visibleFrames>1); + assert.equal(entry.flash.before.opacity,1); + assert.ok(entry.flash.after.opacity<0.95 && entry.flash.after.translate>1); + assert.equal(entry.sample.opacity,1,'the final state alone would pass'); + } + }); +}); + test('client navigation away and back must not replay content that is on screen', {timeout:300000}, async()=> { await withPages(async check=> { for(const viewport of VIEWPORTS) {