Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changepacks/changepack_log_qPizzaodAj-f1Uz8PVvqE.json
Original file line number Diff line number Diff line change
@@ -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"
}
53 changes: 49 additions & 4 deletions crates/devup-mcp-visual/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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<f64>,
/// 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<f64>,
/// Smallest rectangle enclosing pixels above the channel tolerance.
#[serde(default)]
pub changed_bounds: Option<PixelBounds>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub diff_path: Option<String>,
}
Expand Down Expand Up @@ -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,
Expand All @@ -135,15 +157,18 @@ 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(),
reference.height(),
Rgba::<u8>([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
Expand All @@ -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::<u8>([255, 0, 0, 255]));
}
}
Expand Down Expand Up @@ -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,
Expand Down
10 changes: 10 additions & 0 deletions crates/devup-mcp-visual/tests/compare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand Down
85 changes: 83 additions & 2 deletions crates/devup-mcp/src/server/completion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,45 @@ pub struct CompletionInput {
pub routes: Vec<String>,
#[serde(default = "widths")]
pub widths: Vec<u32>,
/// Affected UI states that must have measured passing regression checks.
#[serde(default)]
pub required_regressions: Vec<RequiredRegression>,
/// Explicit affected Figma page or section capture targets.
#[serde(default)]
pub required_visual_states: Vec<RequiredVisualState>,
}

#[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)]
Expand Down Expand Up @@ -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.",
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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);
}
Expand All @@ -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| {
Expand Down Expand Up @@ -561,13 +632,23 @@ pub(super) async fn evaluate(
.cloned()
.collect::<Vec<_>>();
let missing_visual = required_visual.difference(&visual_covered).cloned().collect::<Vec<_>>();
let missing_visual_states = expected_visual_states.difference(&measured_visual_states).cloned().collect::<Vec<_>>();
let missing_regressions = input.required_regressions.iter()
.filter(|requirement| !regression_covered.contains(&requirement.key()))
.collect::<Vec<_>>();
let missing_visual_nodes = input.required_visual_states.iter()
.filter(|requirement| !visual_node_states.contains(&requirement.key()))
.collect::<Vec<_>>();
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)
{
Expand Down Expand Up @@ -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."}),
)
Expand Down
20 changes: 20 additions & 0 deletions crates/devup-mcp/src/server/completion_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
};
Expand Down
4 changes: 3 additions & 1 deletion crates/devup-mcp/src/server/diagnostics/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
};
Expand All @@ -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)
}

Expand Down
2 changes: 2 additions & 0 deletions crates/devup-mcp/src/server/runtime_audit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
},
},
Expand Down
Loading
Loading