From 1959fc3d71bf90ece9db6cbf329f92950e9fc452 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:44:18 +0800 Subject: [PATCH 01/57] M13: design review commands (engine and MCP) --- crates/doc/src/design_review.rs | 111 ++ crates/doc/src/lib.rs | 6 + crates/engine/src/automation/inspect.rs | 2 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/create.rs | 26 +- crates/engine/src/cmd/props.rs | 2 +- crates/engine/src/design/audit.rs | 1318 +++++++++++++++++++++ crates/engine/src/design/fix.rs | 319 +++++ crates/engine/src/design/mod.rs | 378 ++++++ crates/engine/src/design/rules.rs | 132 +++ crates/engine/src/design/tests.rs | 863 ++++++++++++++ crates/engine/src/inspect_fields_tests.rs | 1 + crates/engine/src/lib.rs | 1 + crates/engine/src/prefs.rs | 4 + crates/mcp/src/prompts.rs | 20 +- crates/mcp/src/server.rs | 6 +- crates/mcp/tests/it/protocol.rs | 5 +- 17 files changed, 3183 insertions(+), 12 deletions(-) create mode 100644 crates/doc/src/design_review.rs create mode 100644 crates/engine/src/design/audit.rs create mode 100644 crates/engine/src/design/fix.rs create mode 100644 crates/engine/src/design/mod.rs create mode 100644 crates/engine/src/design/rules.rs create mode 100644 crates/engine/src/design/tests.rs diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs new file mode 100644 index 000000000..c2fce64c8 --- /dev/null +++ b/crates/doc/src/design_review.rs @@ -0,0 +1,111 @@ +//! The design system a file's review follows: how strict it is, the spacing grid, the radii it +//! accepts and the brand accents it knows (`design.configure`). +//! +//! Kept in the document, so a file carries its settings for everyone who opens it, and the audit, +//! the fixer and CI all read the same values. + +use figcraft_color::Color; +use serde::{Deserialize, Serialize}; + +/// How strict `design.audit` is. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum DesignPreset { + /// The rules that catch the usual AI-generated tells. + #[default] + Recommended, + /// Recommended plus the judgment calls (too many accent colours, frames without auto layout). + Strict, + /// Only the findings that keep a design usable: contrast, the type floor, gradient text and + /// clipped text. + Accessibility, +} + +impl DesignPreset { + pub const ALL: [Self; 3] = [Self::Recommended, Self::Strict, Self::Accessibility]; + + pub fn id(self) -> &'static str { + match self { + Self::Recommended => "recommended", + Self::Strict => "strict", + Self::Accessibility => "accessibility", + } + } + + pub fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "recommended" | "default" => Some(Self::Recommended), + "strict" => Some(Self::Strict), + "accessibility" | "a11y" => Some(Self::Accessibility), + _ => None, + } + } +} + +/// The smallest and largest spacing grid a file may set. +pub const GRID_MIN: f64 = 1.0; +pub const GRID_MAX: f64 = 64.0; + +/// Most radii and brand colours a file keeps. +pub const MAX_RADII: usize = 32; +pub const MAX_BRAND_COLORS: usize = 32; + +/// A file's design review settings. The default is the recommended preset on a 4px grid with the +/// 4px radius scale and no brand palette. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct DesignReview { + pub preset: DesignPreset, + /// The spacing and radius grid in pixels (`0`: 4). A value outside [`GRID_MIN`]..=[`GRID_MAX`] + /// reads as the default. + pub grid: f64, + /// The corner radii the design uses, in pixels. Empty: any multiple of the grid from the grid + /// up, or a pill. + pub radii: Vec, + /// The brand's accent colours: they don't count as stray accents (`color.accents`). + pub brand: Vec, + /// Rule ids this file turns off. + pub disabled: Vec, +} + +impl DesignReview { + /// Whether the settings are the default ones (nothing to save). + pub fn is_default(&self) -> bool { + *self == Self::default() + } + + /// The grid in pixels, with invalid values read as 4. + pub fn grid(&self) -> f64 { + if self.grid.is_finite() && (GRID_MIN..=GRID_MAX).contains(&self.grid) { self.grid } else { 4.0 } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn presets_round_trip_by_id() { + for p in DesignPreset::ALL { + assert_eq!(DesignPreset::from_id(p.id()), Some(p)); + } + assert_eq!(DesignPreset::from_id("a11y"), Some(DesignPreset::Accessibility)); + assert_eq!(DesignPreset::from_id("loud"), None); + } + + #[test] + fn a_default_file_does_not_serialize_the_settings_and_junk_grid_reads_as_four() { + let doc = crate::Document::new("Untitled"); + let json = serde_json::to_value(&doc).unwrap(); + assert!(json.get("designReview").is_none(), "{json}"); + let mut settings = DesignReview::default(); + assert!(settings.is_default()); + settings.grid = -3.0; + assert_eq!(settings.grid(), 4.0); + settings.grid = f64::NAN; + assert_eq!(settings.grid(), 4.0); + settings.grid = 8.0; + assert_eq!(settings.grid(), 8.0); + assert!(!settings.is_default()); + } +} diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 81760d718..ac6cf5602 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -12,6 +12,7 @@ pub mod board; mod board_route; pub mod colors; pub mod comments; +pub mod design_review; pub mod facilitation; pub mod geometry; pub mod handoff; @@ -30,6 +31,7 @@ pub use board::*; pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; +pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII}; pub use facilitation::*; pub use figcraft_color as color; pub use figcraft_geom as geom; @@ -229,6 +231,9 @@ pub struct Document { /// Image adjustment presets saved in this file. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub image_presets: Vec, + /// The design system and rules this file's review follows (`design.configure`). + #[serde(default, skip_serializing_if = "DesignReview::is_default")] + pub design_review: DesignReview, /// Annotation categories (`None`: [`AnnotationCategory::defaults`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub annotation_categories: Option>, @@ -285,6 +290,7 @@ impl Document { published: None, color_profile: ColorProfile::Srgb, image_presets: Vec::new(), + design_review: DesignReview::default(), annotation_categories: None, dev_snapshots: BTreeMap::new(), timer: None, diff --git a/crates/engine/src/automation/inspect.rs b/crates/engine/src/automation/inspect.rs index 324635071..d4615bb84 100644 --- a/crates/engine/src/automation/inspect.rs +++ b/crates/engine/src/automation/inspect.rs @@ -40,6 +40,7 @@ pub const NODE_KEYS: &[&str] = &[ "fontFamily", "fontSize", "fontStyle", + "fontWeight", "fontVariations", "gridCell", "grids", @@ -398,6 +399,7 @@ fn text_props(t: &TextData, o: &mut serde_json::Map, options: &In }); insert_prop(o, options, "fontFamily", || json!(t.style.font_family)); insert_prop(o, options, "fontStyle", || json!(t.style.font_style)); + insert_prop(o, options, "fontWeight", || json!(t.style.weight())); insert_prop(o, options, "fontSize", || json!(t.style.font_size)); if !t.style.variations.is_empty() { insert_prop(o, options, "fontVariations", || json!(t.style.variations)); diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 0e90dc198..8ab89c1d5 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -107,6 +107,7 @@ fn registry() -> &'static Registry { list.extend(crate::dev_resources::specs()); list.extend(crate::dev_measurements::specs()); list.extend(crate::distance::specs()); + list.extend(crate::design::specs()); list.extend(crate::collab::specs()); list.extend(crate::branches::specs()); list.extend(crate::plugins::specs()); diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 435c3422a..920ec1113 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -1,7 +1,7 @@ //! Creating nodes. use figcraft_color::{ImageFilters, ImageScaleMode, Paint}; -use figcraft_doc::{Document, Node, NodeId, NodeKind, StrokeCap, TextAutoResize, TextData, VectorNetwork}; +use figcraft_doc::{Document, Node, NodeId, NodeKind, Sizing, StrokeCap, TextAutoResize, TextData, VectorNetwork}; use figcraft_geom::Point; use serde_json::{Value, json}; @@ -99,7 +99,7 @@ pub fn specs() -> Vec { spec!( "text.create", "Text", - "{text | characters, x, y, parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontFamily, …), select? (default true)}", + "{text | characters, x?, y? (ignored inside an auto layout parent), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", true, |s, p| { create_kind(s, p, "text") } ), @@ -275,7 +275,9 @@ pub fn create(s: &mut Session, p: &Value) -> Result { let doc = s.doc()?; let pn = doc.get(parent)?; if !pn.kind.is_container() { - return Err(bad(cmd, format!("{parent} can't contain layers"))); + let name = pn.name.trim(); + let what = if name.is_empty() { pn.kind.type_name().to_string() } else { format!("{} \"{}\"", pn.kind.type_name(), name) }; + return Err(bad(cmd, format!("{parent} ({what}) can't contain layers"))); } if base == "Section" && !doc.takes_sections(parent) { return Err(bad(cmd, "sections go on the page or in other sections")); @@ -371,6 +373,24 @@ pub fn create(s: &mut Session, p: &Value) -> Result { doc.insert(node, parent, index)?; if let Some(Value::Object(props)) = get(p, "props") { super::props::apply(cmd, doc, nid, props)?; + // An auto layout frame hugs the axes the caller left unset — the incumbent's default, and + // the difference between a card and a 100pt-tall box that silently clips its rows. + // Explicit width/height and explicit sizing keep their fixed/fill behaviour. + if doc.node(nid).is_some_and(|n| n.layout.is_some()) { + let asked = |axis: &str, keys: &[&str]| { + let long = if axis == "h" { "width" } else { "height" }; + let short = if axis == "h" { "w" } else { "h" }; + num(p, long).is_some() || props.contains_key(long) || props.contains_key(short) || keys.iter().any(|k| props.contains_key(*k)) + }; + if let Some(n) = doc.node_mut(nid) { + if !asked("h", &["sizingH", "layoutSizingHorizontal"]) { + n.child_layout.sizing_h = Sizing::Hug; + } + if !asked("v", &["sizingV", "layoutSizingVertical"]) { + n.child_layout.sizing_v = Sizing::Hug; + } + } + } } if boolean(p, "select").unwrap_or(true) { ds.selection = vec![nid]; diff --git a/crates/engine/src/cmd/props.rs b/crates/engine/src/cmd/props.rs index 2e5da37bd..f077a31d9 100644 --- a/crates/engine/src/cmd/props.rs +++ b/crates/engine/src/cmd/props.rs @@ -23,7 +23,7 @@ clip, isMask, layout (null|horizontal|vertical|grid|{...}), gap, crossGap, paddi mainAlign (min|center|max, or the auto gaps spaceBetween|spaceAround|spaceEvenly), crossAlign (min|center|max|baseline: first text baselines, horizontal layouts), contentAlign (wrapped lines: auto = packed where crossAlign says | spaceBetween), wrap (rows of a horizontal layout, columns of a vertical one), strokesIncluded (the frame's inside stroke takes up space), reverseZ (canvas stacking: true = first on top), \ columnGap / rowGap (aliases of gap / crossGap), gridColumns, gridRows, columnTracks / rowTracks ([120 | \"1fr\" | \"auto\" | {sizing, value}]), \ gridColumn / gridRow (0-based cell anchor, null = auto), gridColumnSpan, gridRowSpan, gridAlignH / gridAlignV (a grid child's alignment in its cell: min|center|max, auto/null = the frame's), sizingH / sizingV (fixed|hug|fill), \ -absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, \ +absolute (ignore auto layout; follows constraints), minWidth, maxWidth, minHeight, maxHeight (null removes), constraints {horizontal, vertical}, grids, exports, characters, fontFamily, fontStyle, fontWeight (a number: 400 Regular, 600 Semi Bold — the nearest face the family has), \ fontSize, lineHeight (auto|px|\"150%\"), letterSpacing (px|\"2%\"), textAlign (left|center|right|justified), textAlignVertical, textAutoResize \ (widthAndHeight|height|none|truncate), textDecoration, textDecorationStyle (solid|dotted|wavy), textDecorationThickness / textDecorationOffset \ (auto|px|\"10%\" of the font size; the offset runs from the baseline down to an underline's top edge), textDecorationSkipInk (underlines break around descenders), \ diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs new file mode 100644 index 000000000..0a39840e5 --- /dev/null +++ b/crates/engine/src/design/audit.rs @@ -0,0 +1,1318 @@ +//! Walking the scope and turning what it finds into findings. +//! +//! Nothing here edits the document: `design.audit` reads pages and reports. The walk stops at an +//! instance's children (they mirror the main component, which is audited where it lives), skips +//! hidden layers and caps the number of nodes so a huge file cannot stall the app. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{BlendMode, Color, Paint, PaintKind}; +use figcraft_doc::{ + CollectionId, DesignPreset, Document, Effect, EffectKind, LayoutMode, ModeId, Node, NodeId, NodeKind, Shadow, Sizing, StrokeAlign, + TextAutoResize, TextData, VariableValue, +}; +use serde_json::{Map, Value, json}; + +use crate::cmd::lists::paint_binding_key; + +use super::rules::{Severity, rule}; + +/// Most layers one audit looks at; past it the report says `truncated`. +const MAX_NODES: usize = 50_000; +/// Most text layers one audit lays out for the overflow check (text layout is the expensive part). +const MAX_TEXT_MEASURED: usize = 2_000; +/// Most auto layout frames one audit measures for clipped children (bounds are per-subtree). +const MAX_FRAMES_MEASURED: usize = 500; +/// Most siblings or children one backdrop lookup scans before it stops guessing; a flat frame with +/// tens of thousands of layers must not turn every text check into a full scan. +const MAX_BACKDROP_SCAN: usize = 512; + +/// The design system a run checks against: the file's settings (`design.configure`) with an +/// optional preset override from the call. +#[derive(Clone)] +pub(crate) struct Settings { + pub(crate) preset: DesignPreset, + pub(crate) grid: f64, + /// Allowed corner radii; empty: any multiple of the grid from the grid up, or a pill. + pub(crate) radii: Vec, + /// Brand accents as 8-bit RGBA. + pub(crate) brand: Vec<[u8; 4]>, + pub(crate) disabled: BTreeSet, + /// Variable modes the run resolves colours in (empty: the document's own modes). + pub(crate) modes: BTreeMap, + /// The same modes by collection and mode name, for the message and the report. + pub(crate) mode_labels: BTreeMap, +} + +impl Settings { + pub(crate) fn new(doc: &Document, preset: Option) -> Self { + let config = &doc.design_review; + Self { + preset: preset.unwrap_or(config.preset), + grid: config.grid(), + radii: config.radii.iter().copied().filter(|r| r.is_finite() && (0.0..=999.0).contains(r)).collect(), + brand: config.brand.iter().map(|c| c.to_rgba8()).collect(), + disabled: config.disabled.iter().cloned().collect(), + modes: BTreeMap::new(), + mode_labels: BTreeMap::new(), + } + } + + /// Resolve colours in `modes` (collection and mode ids, already checked against the document). + pub(crate) fn in_modes(mut self, doc: &Document, modes: BTreeMap) -> Self { + for (collection, mode) in &modes { + let Some(c) = doc.variables.collection_by_id(collection) else { continue }; + let Some(m) = c.mode_by_id(mode) else { continue }; + self.mode_labels.insert(c.name.clone(), m.name.clone()); + } + self.modes = modes; + self + } + + /// The mode names for a finding's message, when any are overridden. + fn mode_note(&self) -> String { + self.mode_labels.iter().map(|(c, m)| format!("{c}: {m}")).collect::>().join(", ") + } + + /// Whether a run using these settings reports `id`. + pub(crate) fn enabled(&self, id: &str) -> bool { + !self.disabled.contains(id) && super::rules::enabled(id, self.preset) + } + + fn on_grid(&self, v: f64) -> bool { + v.is_finite() && ((v / self.grid) - (v / self.grid).round()).abs() <= 0.01 + } + + pub(crate) fn snap(&self, v: f64) -> f64 { + if v.is_finite() { ((v / self.grid).round() * self.grid).max(0.0) } else { 0.0 } + } + + pub(crate) fn radius_ok(&self, r: f64, w: f64, h: f64) -> bool { + if !r.is_finite() || r <= 0.01 { + return true; + } + let min = w.min(h); + let pill = min > 0.0 && (r - min / 2.0).abs() <= 1.0; + if pill { + return true; + } + if !self.radii.is_empty() { + return self.radii.iter().any(|a| (r - a).abs() <= 0.5); + } + r >= self.grid && self.on_grid(r) + } + + pub(crate) fn snap_radius(&self, r: f64) -> f64 { + if !r.is_finite() { + return self.grid; + } + if !self.radii.is_empty() { + let mut best = self.grid; + let mut distance = f64::INFINITY; + for a in &self.radii { + let d = (r - a).abs(); + if d < distance { + best = *a; + distance = d; + } + } + return best; + } + ((r / self.grid).round() * self.grid).max(self.grid) + } + + /// Whether `c` is one of the file's brand accents (within a few 8-bit steps per channel). + pub(crate) fn is_brand(&self, c: Color) -> bool { + let rgba = c.to_rgba8(); + self.brand.iter().any(|b| (0..4).all(|i| b[i].abs_diff(rgba[i]) <= 12)) + } + + /// The settings a report or the window shows. + pub(crate) fn json(&self) -> Value { + let mut v = json!({"preset": self.preset.id(), "grid": self.grid}); + if !self.mode_labels.is_empty() + && let Some(o) = v.as_object_mut() + { + o.insert("modes".into(), json!(self.mode_labels)); + } + v + } +} + +/// One finding, owned so `design.fix` can act on it after the walk. +#[derive(Clone)] +pub(crate) struct Finding { + pub(crate) rule: &'static str, + pub(crate) severity: Severity, + pub(crate) node: NodeId, + pub(crate) path: String, + pub(crate) message: String, + pub(crate) fixable: bool, + pub(crate) suggestion: Option, + /// The values behind the message, for a localized line in the window and for agents. + pub(crate) details: Option, + /// Why a finding is not fixable: `"bound"` (owned by a variable or style), `"modes"` (read in + /// the chosen variable modes), `None` (needs a decision). Only for `fixable: false`. + pub(crate) reason: Option<&'static str>, +} + +impl Finding { + fn json(&self) -> Value { + let mut v = json!({ + "rule": self.rule, + "severity": self.severity.id(), + "node": self.node, + "path": self.path, + "message": self.message, + "fixable": self.fixable, + }); + if let (Some(s), Some(o)) = (&self.suggestion, v.as_object_mut()) { + o.insert("suggestion".into(), s.clone()); + } + if let (Some(d), Some(o)) = (&self.details, v.as_object_mut()) { + o.insert("details".into(), d.clone()); + } + if !self.fixable + && let Some(o) = v.as_object_mut() + { + o.insert("reason".into(), json!(self.reason.unwrap_or("decision"))); + } + v + } +} + +/// What one walk found. +pub(crate) struct Report { + pub(crate) findings: Vec, + pub(crate) nodes: usize, + pub(crate) truncated: bool, +} + +/// A colour token's default-mode value, for the hardcoded-value check. +struct TokenColor { + name: String, + rgba: [u8; 4], +} + +/// A number token's default-mode value. +struct TokenNumber { + name: String, + value: f64, +} + +/// The file's variables in their collections' default modes. Layers with explicit modes are left +/// out of the token checks (the default value may not be what they show). +struct Tokens { + colors: Vec, + numbers: Vec, +} + +impl Tokens { + fn new(doc: &Document) -> Self { + if doc.variables.variables.is_empty() { + return Self { colors: Vec::new(), numbers: Vec::new() }; + } + let modes: BTreeMap = + doc.variables.collections.iter().filter_map(|c| c.default_mode().map(|m| (c.id.clone(), m.clone()))).collect(); + let mut colors = Vec::new(); + let mut numbers = Vec::new(); + for var in &doc.variables.variables { + let name = if var.name.is_empty() { var.id.clone() } else { var.name.clone() }; + match doc.variables.resolve(&var.id, &modes) { + Some(VariableValue::Color(c)) if c.a > 0.01 => colors.push(TokenColor { name, rgba: c.to_rgba8() }), + Some(VariableValue::Number(n)) if n.is_finite() && n > 0.01 => numbers.push(TokenNumber { name, value: n }), + _ => {} + } + } + colors.sort_by_key(|c| c.rgba); + colors.dedup_by(|a, b| a.rgba == b.rgba); + numbers.sort_by(|a, b| a.value.total_cmp(&b.value)); + numbers.dedup_by(|a, b| (a.value - b.value).abs() <= 1e-6); + Self { colors, numbers } + } + + fn is_empty(&self) -> bool { + self.colors.is_empty() && self.numbers.is_empty() + } + + fn number(&self, value: f64) -> Option<&TokenNumber> { + self.numbers.iter().find(|t| (t.value - value).abs() <= 1e-6) + } + + fn color(&self, color: Color) -> Option<&TokenColor> { + let rgba = color.to_rgba8(); + self.colors.iter().find(|t| t.rgba == rgba) + } +} + +struct Ctx<'a> { + doc: &'a Document, + findings: Vec, + visited: usize, + text_nodes: usize, + /// Font sizes in half-pixels, so 12.5 stays distinct from 12. + sizes: BTreeSet, + families: BTreeSet, + /// Layers carrying at least one shadow. + shadowed: usize, + /// Text layers laid out for the overflow check. + measured: usize, + /// Auto layout frames measured for clipped children. + measured_frames: usize, + tokens: Tokens, + /// The design system this run checks against. + settings: Settings, + /// Distinct accent colours, with the first layer that paints each (for `color.accents`). + accents: BTreeMap<[u8; 4], String>, + truncated: bool, +} + +/// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the +/// ones marked fixable. +pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, anchor_path: &str, scope: &str, settings: &Settings) -> Report { + let mut ctx = Ctx { + doc, + findings: Vec::new(), + visited: 0, + text_nodes: 0, + sizes: BTreeSet::new(), + families: BTreeSet::new(), + shadowed: 0, + measured: 0, + measured_frames: 0, + tokens: Tokens::new(doc), + settings: settings.clone(), + accents: BTreeMap::new(), + truncated: false, + }; + for root in roots { + ctx.walk(*root); + } + ctx.scope_rules(anchor, anchor_path, scope); + Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated } +} + +/// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings +/// (too many type sizes…) point at `anchor`. +pub(crate) fn run( + doc: &Document, + roots: &[NodeId], + scope: &str, + anchor: Option, + anchor_path: &str, + min: Severity, + filter: Option<&BTreeSet>, + preset: Option, + modes: BTreeMap, +) -> Value { + let settings = Settings::new(doc, preset).in_modes(doc, modes); + let report = collect(doc, roots, anchor, anchor_path, scope, &settings); + let shown: Vec<&Finding> = report + .findings + .iter() + .filter(|f| f.severity >= min && settings.enabled(f.rule)) + .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) + .collect(); + let mut counts = [0usize; 3]; + for f in &shown { + counts[f.severity.index()] += 1; + } + let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::()).clamp(0.0, 100.0).round(); + let mut by_rule: BTreeMap<&str, usize> = BTreeMap::new(); + for f in &shown { + *by_rule.entry(f.rule).or_default() += 1; + } + let findings: Vec = shown.into_iter().map(Finding::json).collect(); + let mut out = settings.json(); + if let Some(o) = out.as_object_mut() { + o.insert("scope".into(), json!(scope)); + o.insert("score".into(), json!(score)); + o.insert("counts".into(), json!({"high": counts[2], "medium": counts[1], "low": counts[0]})); + o.insert("byRule".into(), json!(by_rule)); + o.insert("nodes".into(), json!(report.nodes)); + o.insert("findings".into(), json!(findings)); + o.insert("truncated".into(), json!(report.truncated)); + } + out +} + +impl Ctx<'_> { + fn walk(&mut self, root: NodeId) { + let mut stack = vec![(root, String::new())]; + while let Some((id, parent)) = stack.pop() { + if self.visited >= MAX_NODES { + self.truncated = true; + return; + } + let Some(n) = self.doc.node(id) else { continue }; + if !n.visible || n.locked || n.opacity <= 0.001 { + continue; + } + self.visited += 1; + let name = label(n); + let path = if parent.is_empty() { name } else { format!("{parent} / {name}") }; + if !n.is_page() { + self.check_node(n, &path); + } + // An instance's children mirror its main component; audit the main where it lives. + if matches!(&n.kind, NodeKind::Instance { .. }) { + continue; + } + for child in n.children.iter().rev() { + stack.push((*child, path.clone())); + } + } + } + + fn check_node(&mut self, n: &Node, path: &str) { + self.check_naming(n, path); + self.check_spacing(n, path); + self.check_radius(n, path); + self.check_paints(n, path); + self.check_effects(n, path); + if let NodeKind::Text(t) = &n.kind { + self.check_text(n, t, path); + } + self.check_layout(n, path); + self.check_clipping(n, path); + self.note_accents(n); + self.check_tokens(n, path); + } + + fn check_naming(&mut self, n: &Node, path: &str) { + if is_default_name(&n.name) { + self.push_details( + "naming.auto", + n.id, + path, + format!("Layer still has its default name \"{}\"", n.name.trim()), + None, + Some(json!({"name": n.name.trim()})), + ); + } + } + + /// A frame or component holding several layers without auto layout: in the Strict preset. + fn check_layout(&mut self, n: &Node, path: &str) { + if n.layout.is_some() || n.children.len() < 3 { + return; + } + if matches!(n.kind, NodeKind::Frame | NodeKind::Component { .. } | NodeKind::ComponentSet { .. }) { + let count = n.children.len(); + self.push_details( + "layout.no-auto-layout", + n.id, + path, + format!("{count} children with no auto layout"), + None, + Some(json!({"children": count})), + ); + } + } + + /// A fixed-size auto layout frame that clips children which overflow it: the rows exist but + /// are invisible — the usual headless surprise. Hug frames grow, so they cannot clip. + fn check_clipping(&mut self, n: &Node, path: &str) { + if self.measured_frames >= MAX_FRAMES_MEASURED || !n.clip || n.children.is_empty() || n.layout.is_none() { + return; + } + // An instance mirrors its main; the main is audited where it lives. + if matches!(n.kind, NodeKind::Instance { .. }) { + return; + } + let fixed_h = n.child_layout.sizing_h != Sizing::Hug; + let fixed_v = n.child_layout.sizing_v != Sizing::Hug; + if !(fixed_h || fixed_v) { + return; + } + let Some(frame) = self.doc.world_bounds(n.id) else { return }; + let mut u: Option<(f64, f64, f64, f64)> = None; + for child in &n.children { + let Some(c) = self.doc.node(*child) else { continue }; + if !c.visible { + continue; + } + if let Some(b) = self.doc.world_bounds(*child) { + u = Some(match u { + None => (b.x0, b.y0, b.x1, b.y1), + Some((x0, y0, x1, y1)) => (x0.min(b.x0), y0.min(b.y0), x1.max(b.x1), y1.max(b.y1)), + }); + } + } + self.measured_frames += 1; + let Some((ux0, uy0, ux1, uy1)) = u else { return }; + let over_h = fixed_h && (ux1 > frame.x1 + 1.0 || ux0 < frame.x0 - 1.0); + let over_v = fixed_v && (uy1 > frame.y1 + 1.0 || uy0 < frame.y0 - 1.0); + if !(over_h || over_v) { + return; + } + let mut suggestion = Map::new(); + if over_h { + suggestion.insert("sizingH".into(), json!("hug")); + } + if over_v { + suggestion.insert("sizingV".into(), json!("hug")); + } + self.push_details( + "layout.clipped", + n.id, + path, + format!( + "Fixed-size frame clips children that reach {:.0}×{:.0} inside its {:.0}×{:.0}; they are invisible", + ux1 - ux0, + uy1 - uy0, + frame.x1 - frame.x0, + frame.y1 - frame.y0 + ), + Some(Value::Object(suggestion)), + Some(json!({"width": ux1 - ux0, "height": uy1 - uy0, "frameWidth": frame.x1 - frame.x0, "frameHeight": frame.y1 - frame.y0})), + ); + } + + /// Collect the accent colours the scope paints (brand accents and neutrals excluded), for + /// `color.accents`. + fn note_accents(&mut self, n: &Node) { + let paints = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + for p in paints.iter().chain(n.strokes.iter()) { + if !p.visible || p.opacity < 0.5 { + continue; + } + let PaintKind::Solid { color } = &p.kind else { continue }; + if self.settings.is_brand(*color) { + continue; + } + if let Some(rgba) = accent_rgba(*color) + && self.accents.len() < 64 + { + self.accents.entry(rgba).or_insert_with(|| n.name.trim().to_string()); + } + } + } + + fn check_spacing(&mut self, n: &Node, path: &str) { + let Some(al) = &n.layout else { return }; + let mut off = Vec::new(); + let mut suggestion = Map::new(); + if al.mode != LayoutMode::Grid { + if !self.settings.on_grid(al.gap) { + off.push(format!("gap {}", al.gap)); + suggestion.insert("gap".into(), json!(self.settings.snap(al.gap))); + } + if al.wrap && !self.settings.on_grid(al.cross_gap) { + off.push(format!("cross gap {}", al.cross_gap)); + suggestion.insert("crossGap".into(), json!(self.settings.snap(al.cross_gap))); + } + } + let sides = ["top", "right", "bottom", "left"]; + let mut padding_off = false; + for (i, side) in sides.iter().enumerate() { + if let Some(v) = al.padding.get(i).copied().filter(|v| !self.settings.on_grid(*v)) { + off.push(format!("padding {side} {v}")); + padding_off = true; + } + } + if padding_off { + suggestion.insert("padding".into(), json!(al.padding.map(|v| self.settings.snap(v)))); + } + if !off.is_empty() { + let suggestion = if suggestion.is_empty() { None } else { Some(Value::Object(suggestion)) }; + let mut details = Map::new(); + details.insert("grid".into(), json!(self.settings.grid)); + if !self.settings.on_grid(al.gap) { + details.insert("gap".into(), json!(al.gap)); + } + if al.wrap && !self.settings.on_grid(al.cross_gap) { + details.insert("crossGap".into(), json!(al.cross_gap)); + } + if padding_off { + details.insert("padding".into(), json!(al.padding)); + } + self.push_details( + "spacing.off-grid", + n.id, + path, + format!("Off the {}px grid: {}", self.settings.grid, off.join(", ")), + suggestion, + Some(Value::Object(details)), + ); + if [ + "gap", + "columnGap", + "rowGap", + "crossGap", + "padding", + "paddingHorizontal", + "paddingVertical", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + ] + .iter() + .any(|k| n.bound.contains_key(*k)) + { + self.not_fixable(" (bound to a variable)", "bound"); + } + } + } + + fn check_radius(&mut self, n: &Node, path: &str) { + let mut bad: Vec = n.corners.radii.iter().copied().filter(|r| *r > 0.01 && !self.settings.radius_ok(*r, n.width, n.height)).collect(); + if bad.is_empty() { + return; + } + bad.sort_by(f64::total_cmp); + bad.dedup_by(|a, b| (*a - *b).abs() <= 0.01); + let shown: Vec = bad.iter().map(|r| r.to_string()).collect(); + let suggested = self.settings.snap_radius(bad.first().copied().unwrap_or(0.0)); + let suggestion = json!({"cornerRadius": suggested}); + let scale = if self.settings.radii.is_empty() { + format!("any multiple of {}, or a pill", self.settings.grid) + } else { + let list: Vec = self.settings.radii.iter().map(|r| r.to_string()).collect(); + format!("{}, or a pill", list.join(", ")) + }; + self.push_details( + "radius.off-scale", + n.id, + path, + format!("Corner radius off the scale: {} (use {scale})", shown.join(", ")), + Some(suggestion), + Some(json!({"radii": bad, "suggested": suggested})), + ); + if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) { + self.not_fixable(" (bound to a variable)", "bound"); + } + } + + fn check_paints(&mut self, n: &Node, path: &str) { + let is_text = matches!(&n.kind, NodeKind::Text(_)); + let fills: &[Paint] = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + let fills_gradient = fills.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))); + let strokes_gradient = n.strokes.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))); + let run_gradient = match &n.kind { + NodeKind::Text(t) => t + .runs + .iter() + .any(|r| r.style.fills.as_ref().is_some_and(|paints| paints.iter().any(|p| p.visible && matches!(&p.kind, PaintKind::Gradient(_))))), + _ => false, + }; + if fills_gradient || strokes_gradient || run_gradient { + let id = if is_text { "color.gradient-text" } else { "color.gradient" }; + self.push(id, n.id, path, "Painted with a gradient (a hue-to-hue wash is the usual AI tell)".into(), None); + } + // A hairline border is for container-like shapes; an icon's stroke is its whole drawing, + // so full opacity is the intent there, not a stray border. + let container_like = matches!(&n.kind, NodeKind::Frame | NodeKind::Rectangle | NodeKind::Ellipse { .. } | NodeKind::Component { .. }); + if container_like && has_stroke(n) && border_is_strong(self.doc, n) { + self.push( + "color.border-opacity", + n.id, + path, + "Border is more opaque than a hairline (6–10% is enough)".into(), + Some(json!({"strokeOpacity": 0.08})), + ); + if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + } + + fn check_effects(&mut self, n: &Node, path: &str) { + let mut glow = false; + let mut colored = false; + let mut shadows = 0; + for e in n.effects.iter().filter(|e| e.visible) { + if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &e.kind { + shadows += 1; + glow |= is_glow(e); + colored |= is_colored_shadow(s); + } + } + if shadows > 0 { + self.shadowed += 1; + } + if glow { + self.push( + "color.glow", + n.id, + path, + "Shadow has no offset and a large blur, so it reads as a glow".into(), + Some(json!({"removeEffects": ["dropShadow", "innerShadow"]})), + ); + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + if colored { + self.push( + "color.colored-shadow", + n.id, + path, + "Shadow carries a visible hue; shadows read as depth only when neutral".into(), + Some(json!({"neutralShadow": true})), + ); + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + } + + fn check_text(&mut self, n: &Node, t: &TextData, path: &str) { + let chars = t.characters.trim(); + let s = &t.style; + let size = if s.font_size.is_finite() { s.font_size } else { 0.0 }; + let weight = s.weight(); + // A text style (whole layer or a run) or a variable owns the type; changing it here would + // drift from the style the user chose. + let styled = n.styles.text.is_some() + || s.style_id.is_some() + || t.runs.iter().any(|r| r.style.style_id.is_some()) + || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)); + if !chars.is_empty() { + self.text_nodes += 1; + count_size(&mut self.sizes, size); + self.families.insert(family_key(&s.font_family)); + } + for run in &t.runs { + if run.end > run.start { + count_size(&mut self.sizes, run.style.font_size); + self.families.insert(family_key(&run.style.font_family)); + } + } + + if size > 0.0 && size < 11.0 && !chars.is_empty() { + self.push_details( + "type.too-small", + n.id, + path, + format!("Body text at {size}px is below the 11px floor"), + None, + Some(json!({"size": size})), + ); + } + if size >= 20.0 && weight > 600 { + self.push_details( + "type.weight", + n.id, + path, + format!("Heading weight {weight} is heavier than a heading needs"), + Some(json!({"fontWeight": 600})), + Some(json!({"weight": weight})), + ); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + if s.italic() && !chars.is_empty() { + self.push("type.italic", n.id, path, "Interface text is italic".into(), Some(json!({"italic": false}))); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + let tracking = s.letter_spacing.resolve(size); + if tracking.is_finite() && tracking < -0.01 && size > 0.0 && size < 24.0 { + self.push_details( + "type.negative-tracking", + n.id, + path, + format!("Small text is tracked {tracking}px tighter; use size or weight instead"), + Some(json!({"letterSpacing": 0})), + Some(json!({"tracking": tracking})), + ); + if styled { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + + // A run with its own fill makes the text more than one colour; the base fill is not the + // whole story, so the contrast check skips rather than judging the wrong pair. + let mixed_fills = t.runs.iter().any(|r| r.style.fills.is_some()); + self.check_contrast(n, t, path, size, weight, mixed_fills); + + if contains_emoji(&t.characters) || contains_emoji(&n.name) { + self.push("icon.emoji", n.id, path, "Emoji in interface text or a layer name; use a line icon set instead".into(), None); + } + if t.characters.contains('!') || t.characters.contains('!') { + self.push("copy.exclamation", n.id, path, "Copy uses an exclamation mark".into(), Some(json!({"removeExclamations": true}))); + } + if short_label_ends_with_period(chars) { + self.push("copy.trailing-period", n.id, path, "Short label ends with a period".into(), Some(json!({"removeTrailingPeriod": true}))); + } + if has_hype(chars) { + self.push("copy.hype", n.id, path, "Copy uses a hype word (\"AI-powered\", \"supercharge\"…)".into(), None); + } + + // A fixed-width text box whose stored height is shorter than the laid-out text clips or + // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. + if !chars.is_empty() + && n.width > 0.0 + && self.measured < MAX_TEXT_MEASURED + && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) + { + self.measured += 1; + let needed = figcraft_text::layout_cached(t, Some(n.width), None).height; + if needed.is_finite() && needed > n.height + 1.0 { + self.push_details( + "layout.text-overflow", + n.id, + path, + format!("Text needs {needed:.0}px of height but its box is {:.0}px; it clips or overlaps", n.height), + None, + Some(json!({"needed": needed, "height": n.height})), + ); + } + } + } + + /// WCAG contrast for single-colour text, in the run's variable modes when any were given. + fn check_contrast(&mut self, n: &Node, t: &TextData, path: &str, size: f64, weight: u16, mixed_fills: bool) { + if mixed_fills { + return; + } + let (fg, bg) = if self.settings.modes.is_empty() { + (text_color(n, t), backdrop(self.doc, n)) + } else { + (text_color_in(self.doc, n, t, &self.settings.modes), backdrop_in(self.doc, n, Some(&self.settings.modes))) + }; + let (Some(fg), Some(bg)) = (fg, bg) else { return }; + let ratio = fg.contrast(bg); + if !ratio.is_finite() { + return; + } + let large = size >= 24.0 || (size >= 18.0 && weight >= 700); + let need = if large { 3.0 } else { 4.5 }; + if ratio >= need { + return; + } + let mode_note = if self.settings.mode_labels.is_empty() { String::new() } else { format!(" in {}", self.settings.mode_note()) }; + let mut details = json!({"ratio": ratio, "needed": need, "foreground": fg.to_hex(), "background": bg.to_hex()}); + if !self.settings.mode_labels.is_empty() + && let Some(o) = details.as_object_mut() + { + o.insert("modes".into(), json!(self.settings.mode_labels)); + } + self.push_details( + "color.contrast", + n.id, + path, + format!("Contrast {ratio:.2}:1, needs {need:.2}:1 ({} on {}){mode_note}", fg.to_hex(), bg.to_hex()), + None, + Some(details), + ); + if !self.settings.modes.is_empty() { + self.not_fixable(" (read in the chosen variable modes)", "modes"); + } else if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) { + self.not_fixable(" (bound to a style or variable)", "bound"); + } + } + + fn check_tokens(&mut self, n: &Node, path: &str) { + if self.tokens.is_empty() || !n.var_modes.is_empty() { + return; + } + // Colours: a solid paint that is exactly a colour variable's default value, unbound and + // not styled, is a hardcoded token. + let mut hits: Vec<(&str, String, String)> = Vec::new(); + let is_text = matches!(&n.kind, NodeKind::Text(_)); + let fills: &[Paint] = match &n.kind { + NodeKind::Text(t) => t.style.fills.as_deref().unwrap_or(&n.fills), + _ => &n.fills, + }; + if n.styles.fill.is_none() { + for (i, p) in fills.iter().enumerate() { + if !p.visible || paint_binding_key(n, true, i).is_some() { + continue; + } + let Some(c) = p.solid_color() else { continue }; + if let Some(tok) = self.tokens.color(c) { + hits.push((if is_text { "text" } else { "fill" }, c.to_hex(), tok.name.clone())); + } + } + } + if n.styles.stroke.is_none() { + for (i, p) in n.strokes.iter().enumerate() { + if !p.visible || paint_binding_key(n, false, i).is_some() { + continue; + } + let Some(c) = p.solid_color() else { continue }; + if let Some(tok) = self.tokens.color(c) { + hits.push(("stroke", c.to_hex(), tok.name.clone())); + } + } + } + if !hits.is_empty() { + hits.sort(); + hits.dedup(); + let shown: Vec = hits.iter().map(|(kind, hex, token)| format!("{kind} #{hex} = \"{token}\"")).collect(); + let details: Vec = + hits.iter().map(|(kind, hex, token)| json!({"kind": kind, "color": format!("#{hex}"), "token": token})).collect(); + self.push_details( + "token.hardcoded-color", + n.id, + path, + format!("Matches a variable but is not bound: {}", shown.join(", ")), + None, + Some(json!({"hits": details})), + ); + } + + // Numbers: spacing, radii, a text size and opacity. + let mut hits: Vec<(String, f64, String)> = Vec::new(); + { + let mut check = |value: f64, field: &str| { + if value.is_finite() + && value > 0.01 + && let Some(tok) = self.tokens.number(value) + { + hits.push((field.to_string(), value, tok.name.clone())); + } + }; + if let Some(al) = &n.layout { + if al.mode != LayoutMode::Grid && !n.bound.contains_key("gap") { + check(al.gap, "gap"); + } + if al.wrap && !n.bound.contains_key("crossGap") { + check(al.cross_gap, "crossGap"); + } + let keys = ["paddingTop", "paddingRight", "paddingBottom", "paddingLeft"]; + for (i, key) in keys.iter().enumerate() { + if !n.bound.contains_key(*key) + && let Some(v) = al.padding.get(i).copied() + { + check(v, key); + } + } + } + if !["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) + { + for r in n.corners.radii { + check(r, "cornerRadius"); + } + } + if let NodeKind::Text(t) = &n.kind { + let styled = n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()); + if !styled && !n.bound.contains_key("fontSize") { + check(t.style.font_size, "fontSize"); + } + } + if n.opacity < 0.99 && !n.bound.contains_key("opacity") { + check(f64::from(n.opacity), "opacity"); + } + } + if !hits.is_empty() { + hits.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.total_cmp(&b.1))); + hits.dedup_by(|a, b| a.0 == b.0 && (a.1 - b.1).abs() <= 1e-6); + let shown: Vec = hits.iter().map(|(field, value, token)| format!("{field} {value} = \"{token}\"")).collect(); + let details: Vec = hits.iter().map(|(field, value, token)| json!({"field": field, "value": value, "token": token})).collect(); + self.push_details( + "token.hardcoded-number", + n.id, + path, + format!("Matches a variable but is not bound: {}", shown.join(", ")), + None, + Some(json!({"hits": details})), + ); + } + } + + fn scope_rules(&mut self, anchor: Option, path: &str, scope: &str) { + let Some(node) = anchor else { return }; + if self.text_nodes >= 8 { + if self.sizes.len() > 5 { + let sizes: Vec = self.sizes.iter().map(|v| trim_half(*v)).collect(); + self.push_details( + "type.sizes", + node, + path, + format!("{} font sizes in this {scope}: {}", sizes.len(), sizes.join(", ")), + None, + Some(json!({"sizes": sizes, "count": sizes.len()})), + ); + } + if self.families.len() > 2 { + let families: Vec<&str> = self.families.iter().map(String::as_str).collect(); + self.push_details( + "type.families", + node, + path, + format!("{} font families in this {scope}: {}", families.len(), families.join(", ")), + None, + Some(json!({"families": families, "count": families.len()})), + ); + } + } + if self.visited >= 20 && self.shadowed > 5 && self.shadowed * 5 > self.visited { + self.push_details( + "detail.shadow-count", + node, + path, + format!("{} of {} layers carry a shadow or blur", self.shadowed, self.visited), + None, + Some(json!({"shadowed": self.shadowed, "nodes": self.visited})), + ); + } + if self.accents.len() > 2 { + let colors: Vec = self.accents.keys().take(6).map(|c| format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2])).collect(); + self.push_details( + "color.accents", + node, + path, + format!("{} accent colours in this {scope}: {} (keep two)", self.accents.len(), colors.join(", ")), + None, + Some(json!({"count": self.accents.len(), "colors": colors})), + ); + } + } + + fn push(&mut self, id: &'static str, node: NodeId, path: &str, message: String, suggestion: Option) { + self.push_details(id, node, path, message, suggestion, None); + } + + /// A finding whose message has values, with those values in `details` too. + fn push_details(&mut self, id: &'static str, node: NodeId, path: &str, message: String, suggestion: Option, details: Option) { + let Some(r) = rule(id) else { return }; + self.findings.push(Finding { + rule: r.id, + severity: r.severity, + node, + path: path.to_string(), + message, + fixable: r.fixable, + suggestion, + details, + reason: None, + }); + } + + /// Mark the finding just pushed as not auto-fixable, with the reason in its message and as a + /// machine code for the window (`"bound"`: owned by a variable or style; `"modes"`: read in + /// the chosen variable modes). + fn not_fixable(&mut self, note: &str, reason: &'static str) { + if let Some(f) = self.findings.last_mut() { + f.fixable = false; + f.message.push_str(note); + f.reason = Some(reason); + } + } +} + +/// The layer's name, or a stand-in when it has none; long names are cut so paths stay readable. +fn label(n: &Node) -> String { + let name = n.name.trim(); + if name.is_empty() { + return format!("{} {}", n.kind.type_name(), n.id.0); + } + let mut chars = name.chars(); + let short: String = chars.by_ref().take(60).collect(); + if chars.next().is_some() { format!("{short}…") } else { short } +} + +/// A colour that reads as an accent: enough chroma to be a hue rather than a neutral, and neither +/// near-black nor near-white. +fn accent_rgba(c: Color) -> Option<[u8; 4]> { + if !c.a.is_finite() || c.a < 0.5 { + return None; + } + let max = c.r.max(c.g).max(c.b); + let min = c.r.min(c.g).min(c.b); + (max - min >= 0.18 && max >= 0.2 && min <= 0.88).then(|| c.to_rgba8()) +} + +fn has_stroke(n: &Node) -> bool { + n.stroke.weight > 0.01 || n.stroke.sides.is_some_and(|s| s.iter().any(|w| *w > 0.01)) +} + +/// Whether a stroke reads as a strong border rather than a hairline: its colour blended over what +/// is behind it, compared with that backdrop. With no known backdrop, the paint's alpha decides. +fn border_is_strong(doc: &Document, n: &Node) -> bool { + let Some(p) = n.strokes.iter().rev().find(|p| p.visible) else { return false }; + if p.blend != BlendMode::Normal { + return false; + } + let Some(c) = p.solid_color() else { return p.opacity > 0.12 }; + // An inside stroke sits on the layer's own fill; centre and outside strokes sit on what is + // behind it. Default strokes are inside, so a border on a dark panel is judged on that panel. + let bg = if n.stroke.align == StrokeAlign::Inside { solid_fill(n).or_else(|| backdrop(doc, n)) } else { backdrop(doc, n) }; + match bg { + Some(bg) => blend(c, bg).contrast(bg) > 1.5, + None => c.a > 0.12, + } +} + +fn blend(fg: Color, bg: Color) -> Color { + let a = fg.a; + Color::new(fg.r * a + bg.r * (1.0 - a), fg.g * a + bg.g * (1.0 - a), fg.b * a + bg.b * (1.0 - a), 1.0) +} + +fn chroma(c: Color) -> f32 { + let [r, g, b, _] = c.to_rgba8(); + let (max, min) = (r.max(g).max(b) as f32, r.min(g).min(b) as f32); + (max - min) / 255.0 +} + +/// A shadow with no offset and a large blur: it lights the layer instead of giving it depth. +pub(crate) fn is_glow(e: &Effect) -> bool { + if !e.visible { + return false; + } + match &e.kind { + EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) => { + s.offset.0.abs() <= 1.0 && s.offset.1.abs() <= 1.0 && s.radius >= 8.0 && s.color.a > 0.05 + } + _ => false, + } +} + +/// A shadow whose colour carries a visible hue. +pub(crate) fn is_colored_shadow(s: &Shadow) -> bool { + chroma(s.color) > 0.12 && s.color.a > 0.05 +} + +/// The topmost visible solid paint, if it is opaque enough to know what shows through it. +fn solid_fill(n: &Node) -> Option { + let p = n.fills.iter().rev().find(|p| p.visible)?; + // A blend mode changes what the colour looks like over what is behind it; do not guess. + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) || p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + match &p.kind { + PaintKind::Solid { color } if color.a >= 0.95 => Some(*color), + _ => None, + } +} + +/// The colour a text layer's characters show in, when it is a single opaque solid paint. +pub(crate) fn text_color(n: &Node, t: &TextData) -> Option { + let paints = t.style.fills.as_deref().unwrap_or(&n.fills); + let p = paints.iter().rev().find(|p| p.visible)?; + if p.blend != BlendMode::Normal { + return None; + } + if p.opacity < 0.95 { + return None; + } + match &p.kind { + PaintKind::Solid { color } if color.a >= 0.95 => Some(*color), + _ => None, + } +} + +/// `base`, resolved in the layer's variable modes (with `overrides` on top) when the paint's colour +/// is bound to a colour variable. +fn bound_color(doc: &Document, n: &Node, fills: bool, index: usize, base: Color, overrides: &BTreeMap) -> Color { + let Some(key) = paint_binding_key(n, fills, index) else { return base }; + let Some(id) = n.bound.get(key) else { return base }; + let mut modes = doc.modes_for(n.id); + modes.extend(overrides.iter().map(|(c, m)| (c.clone(), m.clone()))); + match doc.variables.resolve(id, &modes) { + Some(VariableValue::Color(c)) => c, + _ => base, + } +} + +/// [`solid_fill`], with bound colours resolved in `overrides` (the layer's own modes first). +fn solid_fill_in(doc: &Document, n: &Node, overrides: &BTreeMap) -> Option { + let index = n.fills.iter().rposition(|p| p.visible)?; + let p = n.fills.get(index)?; + if !matches!(n.blend, BlendMode::Normal | BlendMode::PassThrough) || p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + let PaintKind::Solid { color } = &p.kind else { return None }; + if color.a < 0.95 { + return None; + } + let color = bound_color(doc, n, true, index, *color, overrides); + (color.a >= 0.95).then_some(color) +} + +/// [`text_color`], with bound colours resolved in `overrides`. +fn text_color_in(doc: &Document, n: &Node, t: &TextData, overrides: &BTreeMap) -> Option { + let paints = t.style.fills.as_deref().unwrap_or(&n.fills); + let (index, p) = paints.iter().enumerate().rev().find(|(_, p)| p.visible)?; + if p.blend != BlendMode::Normal || p.opacity < 0.95 { + return None; + } + let PaintKind::Solid { color } = &p.kind else { return None }; + if color.a < 0.95 { + return None; + } + let color = bound_color(doc, n, true, index, *color, overrides); + (color.a >= 0.95).then_some(color) +} + +/// What lies directly behind a layer, or why it cannot be sampled. +enum Behind { + Known(Color), + /// A gradient, image, translucency or partial cover: the audit does not guess. + Unknown, +} + +/// The first opaque solid behind a layer. At each ancestor level, look at the siblings painted +/// below it (z-order, `reverse_z` respected) for the topmost one that covers it, then at that +/// ancestor's own fill. The old version only walked ancestors, so white text on a dark rectangle +/// sibling was compared with the page behind both and reported as unreadable. +pub(crate) fn backdrop(doc: &Document, n: &Node) -> Option { + backdrop_in(doc, n, None) +} + +/// [`backdrop`], resolving bound colours in `overrides` when given. +fn backdrop_in(doc: &Document, n: &Node, overrides: Option<&BTreeMap>) -> Option { + let target = doc.world_bounds(n.id)?; + let mut current = n.id; + for _ in 0..256 { + let node = doc.node(current)?; + let parent_id = node.parent?; + let parent = doc.node(parent_id)?; + if parent.opacity < 0.99 { + return None; + } + match sibling_behind(doc, parent, current, target, overrides) { + Some(Behind::Known(c)) => return Some(c), + Some(Behind::Unknown) => return None, + None => {} + } + if let NodeKind::Page { background, .. } = &parent.kind { + return if background.a >= 0.95 { Some(*background) } else { None }; + } + if parent.fills.iter().any(|p| p.visible) { + return match overrides { + Some(modes) => solid_fill_in(doc, parent, modes), + None => solid_fill(parent), + }; + } + current = parent_id; + } + None +} + +/// The topmost sibling painted below `current` that covers `target`, if it has visible paint. +fn sibling_behind( + doc: &Document, + parent: &Node, + current: NodeId, + target: figcraft_geom::Rect, + overrides: Option<&BTreeMap>, +) -> Option { + let index = parent.children.iter().position(|c| *c == current)?; + let reverse = parent.layout.as_ref().is_some_and(|l| l.reverse_z); + // Last child on top: siblings before `index` are below it. First on top: siblings after are. + let total = if reverse { parent.children.len().saturating_sub(index + 1) } else { index }; + let order: Box> = if reverse { Box::new(index + 1..parent.children.len()) } else { Box::new((0..index).rev()) }; + for i in order.take(MAX_BACKDROP_SCAN) { + let Some(sibling) = parent.children.get(i).and_then(|id| doc.node(*id)) else { continue }; + if let Some(behind) = paint_behind(doc, sibling, target, 1, overrides) { + return Some(behind); + } + } + // Past the cap the topmost paint is unknown, not the page behind the container. + (total > MAX_BACKDROP_SCAN).then_some(Behind::Unknown) +} + +/// The topmost paint a layer (and what it contains) puts under `target`: its children first (they +/// paint above its fill), then its own fill. Text and lines paint glyphs or a stroke, not a +/// background; a container without a fill is entered so a background rectangle inside a group is +/// found too. Clipped children outside the frame are left out. +fn paint_behind( + doc: &Document, + node: &Node, + target: figcraft_geom::Rect, + depth: usize, + overrides: Option<&BTreeMap>, +) -> Option { + if depth > 64 || !node.visible { + return None; + } + let bounds = doc.world_bounds(node.id); + let clipped_away = node.clip && bounds.is_some_and(|b| !contains(b, target)); + if !clipped_away { + let reverse = node.layout.as_ref().is_some_and(|l| l.reverse_z); + let order: Box> = + if reverse { Box::new(0..node.children.len()) } else { Box::new((0..node.children.len()).rev()) }; + for i in order.take(MAX_BACKDROP_SCAN) { + let Some(child) = node.children.get(i).and_then(|id| doc.node(*id)) else { continue }; + if let Some(behind) = paint_behind(doc, child, target, depth + 1, overrides) { + return Some(behind); + } + } + if node.children.len() > MAX_BACKDROP_SCAN { + return Some(Behind::Unknown); + } + } + if matches!(&node.kind, NodeKind::Text(_) | NodeKind::Line) || !node.fills.iter().any(|p| p.visible) { + return None; + } + let b = bounds?; + if !overlaps(b, target) { + return None; + } + if !contains(b, target) || node.opacity < 0.99 { + return Some(Behind::Unknown); + } + let color = match overrides { + Some(modes) => solid_fill_in(doc, node, modes), + None => solid_fill(node), + }; + Some(match color { + Some(c) => Behind::Known(c), + None => Behind::Unknown, + }) +} + +fn overlaps(b: figcraft_geom::Rect, target: figcraft_geom::Rect) -> bool { + b.x0 < target.x1 && target.x0 < b.x1 && b.y0 < target.y1 && target.y0 < b.y1 +} + +fn contains(b: figcraft_geom::Rect, target: figcraft_geom::Rect) -> bool { + b.x0 <= target.x0 && b.y0 <= target.y0 && b.x1 >= target.x1 && b.y1 >= target.y1 +} + +fn count_size(sizes: &mut BTreeSet, size: f64) { + if size.is_finite() && size > 0.0 { + sizes.insert((size * 2.0).round() as i64); + } +} + +fn trim_half(v: i64) -> String { + let n = v as f64 / 2.0; + if (n - n.round()).abs() < 0.01 { format!("{}", n.round() as i64) } else { format!("{n}") } +} + +fn family_key(family: &str) -> String { + let f = family.trim().to_ascii_lowercase(); + if f.is_empty() { "inter".into() } else { f } +} + +fn contains_emoji(s: &str) -> bool { + s.chars().any(|c| { + let u = c as u32; + (0x1F000..=0x1FAFF).contains(&u) || (0x2600..=0x27BF).contains(&u) || matches!(u, 0x2B50 | 0x2B55 | 0x203C | 0x2049) + }) +} + +fn short_label_ends_with_period(s: &str) -> bool { + let s = s.trim_end(); + let body = s.trim_end_matches(['.', '。']).trim_end(); + if body == s || body.is_empty() { + return false; + } + !body.contains('\n') && !body.contains(". ") && body.chars().count() <= 24 +} + +fn has_hype(s: &str) -> bool { + let s = s.to_ascii_lowercase(); + ["ai-powered", "supercharge", "revolutioniz", "game-chang", "unleash the"].iter().any(|w| s.contains(w)) +} + +fn is_default_name(name: &str) -> bool { + let Some((word, number)) = name.trim().rsplit_once(' ') else { return false }; + const KINDS: [&str; 13] = + ["Frame", "Rectangle", "Ellipse", "Group", "Text", "Component", "Section", "Vector", "Line", "Polygon", "Star", "Slice", "Boolean"]; + KINDS.contains(&word) && !number.is_empty() && number.chars().all(|c| c.is_ascii_digit()) +} diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs new file mode 100644 index 000000000..e6a5e6d7e --- /dev/null +++ b/crates/engine/src/design/fix.rs @@ -0,0 +1,319 @@ +//! `design.fix`: repair the findings `design.audit` marks fixable, as one undo step. +//! +//! Every repair is the safe, unambiguous one the audit already suggested: spacing snapped to the +//! 4px grid, radii to the scale, heavy headings to Semi Bold, italic and negative tracking removed, +//! glows taken out, shadow colours neutralised and strong borders thinned. Content rules (copy, +//! naming) and gradients are left alone: those need a decision, not arithmetic. + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_color::{Color, PaintKind}; +use figcraft_doc::{DesignPreset, Document, EffectKind, LayoutMode, LetterSpacing, Node, NodeId, NodeKind, TextData, TextStyle}; +use serde_json::{Value, json}; + +use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; + +/// Fix what `roots` made fixable among `filter`'s rules. With `exact`, only findings on the roots +/// themselves are repaired, not findings on their descendants. `dry_run` reports the same counts +/// without changing the document. +pub(crate) fn run( + doc: &mut Document, + roots: &[NodeId], + anchor: Option, + anchor_path: &str, + scope: &str, + preset: Option, + filter: Option<&BTreeSet>, + exact: bool, + dry_run: bool, +) -> Value { + let settings = Settings::new(doc, preset); + let before = collect(doc, roots, anchor, anchor_path, scope, &settings); + let targets: Vec<(NodeId, &'static str)> = before + .findings + .iter() + .filter(|f| f.fixable && settings.enabled(f.rule)) + .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) + .filter(|f| !exact || roots.contains(&f.node)) + .map(|f| (f.node, f.rule)) + .collect(); + let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new(); + let mut changed = 0usize; + let mut skipped = 0usize; + if dry_run { + changed = targets.len(); + for (_, rule) in &targets { + *by_rule.entry(*rule).or_default() += 1; + } + } else { + for (id, rule) in &targets { + match apply(doc, *id, rule, &settings) { + Some(true) => { + changed += 1; + *by_rule.entry(*rule).or_default() += 1; + } + _ => skipped += 1, + } + } + } + let after = collect(doc, roots, anchor, anchor_path, scope, &settings); + json!({ + "scope": scope, + "dryRun": dry_run, + "changed": changed, + "skipped": skipped, + "byRule": by_rule, + "before": tally(&before, &settings), + "after": tally(&after, &settings), + }) +} + +fn tally(report: &Report, settings: &Settings) -> Value { + let shown: Vec<&super::audit::Finding> = report.findings.iter().filter(|f| settings.enabled(f.rule)).collect(); + let mut counts = [0usize; 3]; + for f in &shown { + counts[f.severity.index()] += 1; + } + let score = (100.0 - shown.iter().map(|f| f.severity.penalty()).sum::()).clamp(0.0, 100.0).round(); + json!({ + "score": score, + "counts": {"high": counts[2], "medium": counts[1], "low": counts[0]}, + "nodes": report.nodes, + "findings": shown.len(), + }) +} + +/// Apply one finding's repair. `None` when the layer is gone or the repair does not apply to it; +/// `Some(false)` when it applied to nothing (a no-op the caller counts as skipped). +fn apply(doc: &mut Document, id: NodeId, rule: &str, settings: &Settings) -> Option { + if rule == "color.contrast" { + return apply_contrast(doc, id); + } + let n = doc.node_mut(id)?; + match rule { + "spacing.off-grid" => apply_spacing(n, settings), + "radius.off-scale" => { + if ["cornerRadius", "topLeftRadius", "topRightRadius", "bottomRightRadius", "bottomLeftRadius"].iter().any(|k| n.bound.contains_key(*k)) { + return Some(false); + } + apply_radius(n, settings) + } + "type.weight" | "type.italic" | "type.negative-tracking" => { + if text_styled(n) || ["fontSize", "fontStyle", "fontWeight", "letterSpacing"].iter().any(|k| n.bound.contains_key(*k)) { + return Some(false); + } + match rule { + "type.weight" => apply_text(n, cap_weight), + "type.italic" => apply_text(n, unitalic), + _ => apply_text(n, zero_tracking), + } + } + "color.glow" | "color.colored-shadow" => { + if n.styles.effect.is_some() || n.bound.keys().any(|k| k.starts_with("effects/")) { + return Some(false); + } + if rule == "color.glow" { apply_glow(n) } else { apply_neutral_shadows(n) } + } + "color.border-opacity" => { + if n.styles.stroke.is_some() || n.bound.keys().any(|k| k.starts_with("strokes/")) { + return Some(false); + } + apply_border(n) + } + _ => Some(false), + } +} + +/// A text layer whose type comes from a text style (the whole layer or one run). +fn text_styled(n: &Node) -> bool { + match &n.kind { + NodeKind::Text(t) => n.styles.text.is_some() || t.style.style_id.is_some() || t.runs.iter().any(|r| r.style.style_id.is_some()), + _ => false, + } +} + +/// Darken (or lighten, on a dark backdrop) the text colour until it reaches the WCAG ratio. The +/// hue is kept as far as the blend allows; when even black or white cannot reach the ratio, the +/// text is left as it is and counted as skipped. +fn apply_contrast(doc: &mut Document, id: NodeId) -> Option { + let n = doc.node(id)?; + let NodeKind::Text(t) = &n.kind else { return Some(false) }; + if n.styles.fill.is_some() || n.bound.keys().any(|k| k.starts_with("fills/")) { + return Some(false); + } + let fg = text_color(n, t)?; + let bg = backdrop(doc, n)?; + let size = t.style.font_size; + let large = size >= 24.0 || (size >= 18.0 && t.style.weight() >= 700); + let need = if large { 3.0 } else { 4.5 }; + if fg.contrast(bg) >= need { + return Some(false); + } + let fixed = accessible(fg, bg, need); + if fixed.contrast(bg) < need { + return Some(false); + } + let n = doc.node_mut(id)?; + let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; + let paints = match &mut t.style.fills { + Some(fills) => fills, + None => &mut n.fills, + }; + let paint = paints.iter_mut().rev().find(|p| p.visible && matches!(&p.kind, PaintKind::Solid { .. }))?; + paint.opacity = 1.0; + if let PaintKind::Solid { color } = &mut paint.kind { + *color = fixed.with_alpha(fg.a); + Some(true) + } else { + Some(false) + } +} + +/// The closest shade of `fg` towards black (light backdrop) or white (dark backdrop) that meets +/// `need` against `bg`, by bisection. +fn accessible(fg: Color, bg: Color, need: f32) -> Color { + let target = if bg.luminance() > 0.5 { Color::BLACK } else { Color::WHITE }; + let (mut lo, mut hi) = (0.0f32, 1.0f32); + let mut best = target; + for _ in 0..24 { + let t = (lo + hi) / 2.0; + let c = Color::new(fg.r + (target.r - fg.r) * t, fg.g + (target.g - fg.g) * t, fg.b + (target.b - fg.b) * t, 1.0); + if c.contrast(bg) >= need { + best = c; + hi = t; + } else { + lo = t; + } + } + best +} + +fn apply_spacing(n: &mut Node, settings: &Settings) -> Option { + // Any spacing binding owns the whole layout value: fixing one field next to a token would + // leave a mixed layout and is not what the audit promised. + if [ + "gap", + "columnGap", + "rowGap", + "crossGap", + "padding", + "paddingHorizontal", + "paddingVertical", + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + ] + .iter() + .any(|k| n.bound.contains_key(*k)) + { + return Some(false); + } + let al = n.layout.as_mut()?; + let mut changed = false; + if al.mode != LayoutMode::Grid { + let gap = settings.snap(al.gap); + if (gap - al.gap).abs() > 1e-6 { + al.gap = gap; + changed = true; + } + if al.wrap { + let cross = settings.snap(al.cross_gap); + if (cross - al.cross_gap).abs() > 1e-6 { + al.cross_gap = cross; + changed = true; + } + } + } + for side in &mut al.padding { + let value = settings.snap(*side); + if (value - *side).abs() > 1e-6 { + *side = value; + changed = true; + } + } + Some(changed) +} + +fn apply_radius(n: &mut Node, settings: &Settings) -> Option { + let (w, h) = (n.width, n.height); + let pill = w.min(h); + let mut changed = false; + for r in &mut n.corners.radii { + if *r > 0.01 && !settings.radius_ok(*r, w, h) { + *r = if pill > 0.0 && (*r - pill / 2.0).abs() <= 1.0 { pill / 2.0 } else { settings.snap_radius(*r) }; + changed = true; + } + } + Some(changed) +} + +/// Run `f` over a text layer's base style and its runs; true when any style changed. +fn apply_text(n: &mut Node, f: fn(&mut TextStyle) -> bool) -> Option { + let NodeKind::Text(t) = &mut n.kind else { return Some(false) }; + let TextData { style, runs, .. } = t; + let mut changed = f(style); + for run in runs { + changed |= f(&mut run.style); + } + Some(changed) +} + +fn cap_weight(s: &mut TextStyle) -> bool { + if s.font_size >= 20.0 && s.weight() > 600 { + s.set_font_style("Semi Bold"); + true + } else { + false + } +} + +fn unitalic(s: &mut TextStyle) -> bool { + if !s.italic() { + return false; + } + let words: Vec<&str> = s.font_style.split_whitespace().filter(|w| !w.eq_ignore_ascii_case("italic")).collect(); + let name = if words.is_empty() { "Regular".to_string() } else { words.join(" ") }; + s.set_font_style(name); + true +} + +fn zero_tracking(s: &mut TextStyle) -> bool { + let px = s.letter_spacing.resolve(s.font_size); + if s.font_size > 0.0 && s.font_size < 24.0 && px.is_finite() && px < -0.01 { + s.letter_spacing = LetterSpacing::Percent(0.0); + true + } else { + false + } +} + +fn apply_glow(n: &mut Node) -> Option { + let before = n.effects.len(); + n.effects.retain(|e| !is_glow(e)); + Some(n.effects.len() != before) +} + +fn apply_neutral_shadows(n: &mut Node) -> Option { + let mut changed = false; + for e in &mut n.effects { + if let EffectKind::DropShadow(s) | EffectKind::InnerShadow(s) = &mut e.kind + && is_colored_shadow(s) + { + s.color = Color::new(0.0, 0.0, 0.0, s.color.a); + changed = true; + } + } + Some(changed) +} + +fn apply_border(n: &mut Node) -> Option { + let mut changed = false; + for p in &mut n.strokes { + if p.visible && p.opacity > 0.08 { + p.opacity = 0.08; + changed = true; + } + } + Some(changed) +} diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs new file mode 100644 index 000000000..7e8229323 --- /dev/null +++ b/crates/engine/src/design/mod.rs @@ -0,0 +1,378 @@ +//! Design review: deterministic checks for the usual AI-generated interface tells. +//! +//! `design.audit` reads a selection, a page or the whole document and reports what a designer +//! would fix first — spacing off the 4px grid, radii outside the scale, too many type sizes, +//! gradient text, glows, low-contrast text, emoji labels. It changes nothing. `design.fix` (the +//! planned follow-up) repairs the findings marked `fixable`. +//! +//! The rules are our own reading of the public "unslop" checklist (CC BY 4.0, heydamir/unslop): +//! only the ideas, no text or assets from it. + +mod audit; +mod fix; +mod rules; + +#[cfg(test)] +mod tests; + +use std::collections::{BTreeMap, BTreeSet}; + +use figcraft_doc::{CollectionId, DesignPreset, DesignReview, Document, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII, ModeId, NodeId}; +use serde_json::{Value, json}; + +use crate::cmd::CommandSpec; +use crate::params; +use crate::{EngineError, Result, Session, bad, spec}; +use rules::{RULES, Severity, presets_of, rule}; + +pub fn specs() -> Vec { + vec![ + spec!( + "design.audit", + "Check design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + false, + audit_cmd + ), + spec!( + "design.fix", + "Fix design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", + true, + fix_cmd + ), + spec!( + "design.assert", + "Assert design", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists or the score is below minScore; read-only, for CI", + false, + assert_cmd + ), + spec!( + "design.configure", + "Configure design review", + "{preset?: recommended|strict|accessibility, grid?: 1-64 (px, default 4), radii?: [px] (empty: the grid scale and a pill), brand?: [colour] (accent colours the file owns), disabled?: [rule ids] (rules off in this file), reset?: bool} → {preset, grid, radii, brand, disabled} changes the file's design review settings in one undo step; audit, fix and assert use them from then on", + true, + configure_cmd + ), + spec!( + "design.rules", + "List design rules", + "{} → {rules: [{id, severity, fixable, description, presets}], presets: [{id, description}]}", + false, + |_, _| Ok(json!({ + "rules": RULES.iter().map(|r| json!({ + "id": r.id, + "severity": r.severity.id(), + "fixable": r.fixable, + "description": r.description, + "presets": presets_of(r.id), + })).collect::>(), + "presets": DesignPreset::ALL.iter().map(|p| json!({ + "id": p.id(), + "description": preset_description(*p), + })).collect::>(), + })) + ), + ] +} + +fn audit_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.audit", p)?; + let min = severity_arg("design.audit", p)?; + let filter = filter_arg("design.audit", p)?; + let preset = preset_arg("design.audit", p)?; + let modes = modes_arg("design.audit", p, s.doc()?)?; + Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes)) +} + +fn fix_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.fix", p)?; + let filter = filter_arg("design.fix", p)?; + let preset = preset_arg("design.fix", p)?; + let exact = params::boolean(p, "exact").unwrap_or(false); + let dry = params::boolean(p, "dryRun").unwrap_or(false); + Ok(fix::run(s.doc_mut()?, &roots, anchor, &path, &label, preset, filter.as_ref(), exact, dry)) +} + +/// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error +/// that names the counts when it does not. +fn assert_cmd(s: &mut Session, p: &Value) -> Result { + let (label, roots, anchor, path) = scope_of(s, "design.assert", p)?; + let filter = filter_arg("design.assert", p)?; + let fail_on = severity_named("design.assert", p, "failOn", Severity::High)?; + let preset = preset_arg("design.assert", p)?; + let modes = modes_arg("design.assert", p, s.doc()?)?; + let min_score = match params::get(p, "minScore") { + None => 0.0, + Some(v) => match params::f64_of(v) { + Some(v) if (0.0..=100.0).contains(&v) => v, + _ => return Err(bad("design.assert", "`minScore` must be a number between 0 and 100")), + }, + }; + // The score covers the whole review (as the window shows it); only findings at or above + // `failOn` fail the gate. + let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes); + let failing: Vec<&Value> = report["findings"] + .as_array() + .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) + .unwrap_or_default(); + let score = report["score"].as_f64().unwrap_or(0.0); + if !failing.is_empty() || score < min_score { + let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); + for f in &failing { + if let Some(rule) = f["rule"].as_str() { + *by_rule.entry(rule).or_default() += 1; + } + } + let rules: Vec = by_rule.iter().take(4).map(|(rule, count)| format!("{rule} ×{count}")).collect(); + let detail = if rules.is_empty() { String::new() } else { format!(" ({})", rules.join(", ")) }; + return Err(EngineError::Other(format!( + "design review failed: score {score:.0}, {} finding(s) at {} or above{detail}", + failing.len(), + fail_on.id() + ))); + } + Ok(json!({"ok": true, "score": score, "counts": report["counts"]})) +} + +fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result { + match params::string(p, key).map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(default), + Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`{key}` must be low, medium or high, not `{s}`"))), + } +} + +fn preset_arg(cmd: &str, p: &Value) -> Result> { + match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(None), + Some(s) => { + DesignPreset::from_id(&s).map(Some).ok_or_else(|| bad(cmd, format!("`preset` must be recommended, strict or accessibility, not `{s}`"))) + } + } +} + +fn preset_description(preset: DesignPreset) -> &'static str { + match preset { + DesignPreset::Recommended => "The usual AI-generated tells", + DesignPreset::Strict => "Recommended plus accent colours and frames without auto layout", + DesignPreset::Accessibility => "Contrast, the type floor, gradient text and clipped text only", + } +} + +/// The variable modes a run resolves colours in: `{collection: mode}`, by id or by name. +fn modes_arg(cmd: &str, p: &Value, doc: &Document) -> Result> { + let Some(v) = params::get(p, "modes") else { return Ok(BTreeMap::new()) }; + let Value::Object(map) = v else { return Err(bad(cmd, "`modes` must be an object of collection → mode")) }; + if map.len() > 64 { + return Err(bad(cmd, "at most 64 collections in `modes`")); + } + let mut out = BTreeMap::new(); + for (collection_key, mode_value) in map { + let Some(mode_key) = mode_value.as_str().map(str::trim).filter(|s| !s.is_empty()) else { + return Err(bad(cmd, "`modes` values must be mode ids or names")); + }; + let Some(collection) = doc.variables.collection(collection_key.trim()) else { + return Err(bad(cmd, format!("unknown collection `{collection_key}`"))); + }; + let Some(mode) = collection.find_mode(mode_key) else { + return Err(bad(cmd, format!("unknown mode `{mode_key}` in `{}`", collection.name))); + }; + out.insert(collection.id.clone(), mode.id.clone()); + } + Ok(out) +} + +/// `design.configure`: change the file's design system and rules in one undo step. +fn configure_cmd(s: &mut Session, p: &Value) -> Result { + let mut config = if params::boolean(p, "reset").unwrap_or(false) { DesignReview::default() } else { s.doc()?.design_review.clone() }; + if let Some(preset) = preset_arg("design.configure", p)? { + config.preset = preset; + } + if let Some(v) = params::get(p, "grid") { + let grid = params::f64_of(v) + .filter(|g| g.is_finite() && (GRID_MIN..=GRID_MAX).contains(g)) + .ok_or_else(|| bad("design.configure", format!("`grid` must be a number from {GRID_MIN} to {GRID_MAX}")))?; + config.grid = grid; + } + if let Some(v) = params::get(p, "radii") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`radii` must be an array of numbers")) }; + if items.len() > MAX_RADII { + return Err(bad("design.configure", format!("at most {MAX_RADII} radii"))); + } + let mut radii = Vec::new(); + for item in items { + let r = params::f64_of(item) + .filter(|r| r.is_finite() && (0.0..=999.0).contains(r)) + .ok_or_else(|| bad("design.configure", "each radius must be a number from 0 to 999"))?; + radii.push((r * 100.0).round() / 100.0); + } + radii.sort_by(f64::total_cmp); + radii.dedup_by(|a, b| (*a - *b).abs() <= 1e-6); + config.radii = radii; + } + if let Some(v) = params::get(p, "brand") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`brand` must be an array of colours")) }; + if items.len() > MAX_BRAND_COLORS { + return Err(bad("design.configure", format!("at most {MAX_BRAND_COLORS} brand colours"))); + } + let mut brand = Vec::new(); + for item in items { + let color = params::color_of(item).ok_or_else(|| bad("design.configure", "each brand colour must be a colour"))?; + if color.a > 0.05 { + brand.push(color); + } + } + config.brand = brand; + } + if let Some(v) = params::get(p, "disabled") { + let Value::Array(items) = v else { return Err(bad("design.configure", "`disabled` must be an array of rule ids")) }; + let mut ids = BTreeSet::new(); + for item in items { + let Some(id) = item.as_str().map(str::trim) else { + return Err(bad("design.configure", "`disabled` must be an array of rule ids")); + }; + if rule(id).is_none() { + return Err(bad("design.configure", format!("unknown rule `{id}` (run design.rules for the list)"))); + } + ids.insert(id.to_string()); + } + config.disabled = ids.into_iter().collect(); + } + if s.doc()?.design_review == config { + return Ok(settings_json(&config)); + } + let doc = s.doc_mut()?; + doc.design_review = config; + Ok(settings_json(&doc.design_review)) +} + +fn settings_json(config: &DesignReview) -> Value { + let brand: Vec = config + .brand + .iter() + .map(|c| { + let rgba = c.to_rgba8(); + format!("#{:02X}{:02X}{:02X}", rgba[0], rgba[1], rgba[2]) + }) + .collect(); + json!({ + "preset": config.preset.id(), + "grid": config.grid(), + "radii": config.radii, + "brand": brand, + "disabled": config.disabled, + }) +} + +/// The layers a command works on, its scope label, the layer aggregate findings point at and that +/// layer's path. +fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { + let doc = s.doc()?; + // `ids` names the layers directly (the review window fixes only the findings the user kept). + if let Some(v) = params::get(p, "ids") { + let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + let mut ids = Vec::new(); + for item in items { + let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + ids.push(id); + } + let roots = top_most(doc, &ids); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + return Ok(("selection".into(), roots, anchor, path)); + } + let scope = scope_arg(cmd, p)?; + let selection = s.selection(); + let page = s.page()?; + let (roots, label, anchor, path) = match scope.as_deref() { + None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)), + None => selection_scope(doc, &selection), + Some("selection") => selection_scope(doc, &selection), + Some("page") => (vec![page], "page", Some(page), node_label(doc, page)), + Some("document") => { + let roots = doc.pages.clone(); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + (roots, "document", anchor, path) + } + Some(other) => return Err(bad(cmd, format!("`scope` must be selection, page or document, not `{other}`"))), + }; + Ok((label.to_string(), roots, anchor, path)) +} + +fn selection_scope(doc: &Document, selection: &[NodeId]) -> (Vec, &'static str, Option, String) { + let roots = top_most(doc, selection); + let anchor = roots.first().copied(); + let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); + (roots, "selection", anchor, path) +} + +fn scope_arg(cmd: &str, p: &Value) -> Result> { + let Some(v) = params::get(p, "scope") else { return Ok(None) }; + let Value::String(s) = v else { return Err(bad(cmd, "`scope` must be a string")) }; + let s = s.trim().to_ascii_lowercase(); + if s.is_empty() { + return Ok(None); + } + if matches!(s.as_str(), "selection" | "page" | "document") { + Ok(Some(s)) + } else { + Err(bad(cmd, format!("`scope` must be selection, page or document, not `{s}`"))) + } +} + +fn severity_arg(cmd: &str, p: &Value) -> Result { + match params::string(p, "minSeverity").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { + None => Ok(Severity::Low), + Some(s) => Severity::from_id(&s).ok_or_else(|| bad(cmd, format!("`minSeverity` must be low, medium or high, not `{s}`"))), + } +} + +fn filter_arg(cmd: &str, p: &Value) -> Result>> { + let Some(v) = params::get(p, "rules") else { return Ok(None) }; + let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + let mut set = BTreeSet::new(); + for item in items { + let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + let id = s.trim(); + if rule(id).is_none() { + return Err(bad(cmd, format!("unknown rule `{id}` (run design.rules for the list)"))); + } + set.insert(id.to_string()); + } + Ok(Some(set)) +} + +/// Selected layers without the ones whose ancestor is selected too: their subtrees would be +/// audited twice. +fn top_most(doc: &Document, ids: &[NodeId]) -> Vec { + let mut out: Vec = Vec::new(); + for id in ids { + if out.contains(id) { + continue; + } + let mut parent = doc.node(*id).and_then(|n| n.parent); + let mut depth = 0; + let mut nested = false; + while let Some(pid) = parent { + if depth > 256 { + break; + } + if ids.contains(&pid) { + nested = true; + break; + } + parent = doc.node(pid).and_then(|n| n.parent); + depth += 1; + } + if !nested { + out.push(*id); + } + } + out +} + +fn node_label(doc: &Document, id: NodeId) -> String { + doc.node(id).map(|n| n.name.trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Layer {}", id.0)) +} diff --git a/crates/engine/src/design/rules.rs b/crates/engine/src/design/rules.rs new file mode 100644 index 000000000..89fdc700e --- /dev/null +++ b/crates/engine/src/design/rules.rs @@ -0,0 +1,132 @@ +//! The rules `design.audit` checks, with the severity and fixability the report carries. + +use figcraft_doc::DesignPreset; + +/// How much a finding matters: `High` first. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub(crate) enum Severity { + Low, + Medium, + High, +} + +impl Severity { + pub(crate) fn id(self) -> &'static str { + match self { + Severity::Low => "low", + Severity::Medium => "medium", + Severity::High => "high", + } + } + + pub(crate) fn from_id(s: &str) -> Option { + match s.trim().to_ascii_lowercase().as_str() { + "low" => Some(Severity::Low), + "medium" | "med" => Some(Severity::Medium), + "high" => Some(Severity::High), + _ => None, + } + } + + /// `0` for low, `1` for medium, `2` for high. + pub(crate) fn index(self) -> usize { + match self { + Severity::Low => 0, + Severity::Medium => 1, + Severity::High => 2, + } + } + + /// The points a finding of this severity takes off the score. + pub(crate) fn penalty(self) -> f64 { + match self { + Severity::Low => 0.5, + Severity::Medium => 2.0, + Severity::High => 5.0, + } + } +} + +/// One check: what it looks for, how much it matters and whether `design.fix` can repair it. +pub(crate) struct Rule { + pub id: &'static str, + pub severity: Severity, + /// The planned fixer can change this without guessing (see `docs/design-review.md`). + pub fixable: bool, + pub description: &'static str, +} + +pub(crate) const RULES: &[Rule] = &[ + Rule { id: "spacing.off-grid", severity: Severity::Medium, fixable: true, description: "Auto layout gap or padding is not on the 4px grid" }, + Rule { id: "radius.off-scale", severity: Severity::Low, fixable: true, description: "A corner radius is not on the 4px scale or a pill" }, + Rule { id: "type.sizes", severity: Severity::Medium, fixable: false, description: "More than five font sizes in one scope" }, + Rule { id: "type.families", severity: Severity::Medium, fixable: false, description: "More than two font families in one scope" }, + Rule { id: "type.weight", severity: Severity::Low, fixable: true, description: "A heading uses a weight above 600" }, + Rule { id: "type.italic", severity: Severity::Low, fixable: true, description: "Interface text is italic" }, + Rule { id: "type.too-small", severity: Severity::Medium, fixable: false, description: "Body text is smaller than 11px" }, + Rule { id: "type.negative-tracking", severity: Severity::Low, fixable: true, description: "Small text has negative letter spacing" }, + Rule { id: "color.gradient", severity: Severity::Medium, fixable: false, description: "A shape is filled or stroked with a gradient" }, + Rule { id: "color.gradient-text", severity: Severity::High, fixable: false, description: "Text is painted with a gradient" }, + Rule { + id: "color.glow", + severity: Severity::Medium, + fixable: true, + description: "A shadow has no offset and a large blur, so it reads as a glow", + }, + Rule { id: "color.colored-shadow", severity: Severity::Low, fixable: true, description: "A shadow has a visible hue instead of a neutral" }, + Rule { id: "color.border-opacity", severity: Severity::Low, fixable: true, description: "A border is more opaque than a hairline" }, + Rule { id: "color.contrast", severity: Severity::High, fixable: true, description: "Text contrast is below 4.5:1 (3:1 for large text)" }, + Rule { id: "color.accents", severity: Severity::Medium, fixable: false, description: "More than two accent colours in one scope (Strict)" }, + Rule { id: "token.hardcoded-color", severity: Severity::Low, fixable: false, description: "A colour matches a variable but is not bound to it" }, + Rule { + id: "token.hardcoded-number", + severity: Severity::Low, + fixable: false, + description: "A spacing, radius, size or opacity value matches a variable but is not bound", + }, + Rule { id: "icon.emoji", severity: Severity::Low, fixable: false, description: "Text or a layer name contains an emoji" }, + Rule { id: "copy.exclamation", severity: Severity::Low, fixable: false, description: "Interface copy uses an exclamation mark" }, + Rule { id: "copy.trailing-period", severity: Severity::Low, fixable: false, description: "A short label ends with a period" }, + Rule { id: "copy.hype", severity: Severity::Low, fixable: false, description: "Copy uses hype words such as \"AI-powered\"" }, + Rule { id: "naming.auto", severity: Severity::Low, fixable: false, description: "A layer still has its default auto name (Frame 12)" }, + Rule { id: "detail.shadow-count", severity: Severity::Low, fixable: false, description: "Shadows and blurs sit on too many layers" }, + Rule { + id: "layout.no-auto-layout", + severity: Severity::Low, + fixable: false, + description: "A frame or component with several children has no auto layout (Strict)", + }, + Rule { + id: "layout.text-overflow", + severity: Severity::High, + fixable: false, + description: "A fixed-width text box is shorter than the text it holds, so it clips or overlaps", + }, + Rule { + id: "layout.clipped", + severity: Severity::High, + fixable: false, + description: "A fixed-size auto layout frame clips children that overflow it, so they are invisible", + }, +]; + +pub(crate) fn rule(id: &str) -> Option<&'static Rule> { + RULES.iter().find(|r| r.id == id) +} + +/// Whether `preset` checks `id`. Recommended and Strict check every rule except the Strict-only +/// ones; Accessibility checks only the findings that keep a design usable. +pub(crate) fn enabled(id: &str, preset: DesignPreset) -> bool { + match preset { + DesignPreset::Recommended => !matches!(id, "color.accents" | "layout.no-auto-layout"), + DesignPreset::Strict => true, + DesignPreset::Accessibility => { + matches!(id, "color.contrast" | "color.gradient-text" | "type.too-small" | "layout.text-overflow" | "layout.clipped") + } + } +} + +/// The presets that check `id`, for `design.rules`. +pub(crate) fn presets_of(id: &str) -> Vec<&'static str> { + DesignPreset::ALL.iter().copied().filter(|p| enabled(id, *p)).map(DesignPreset::id).collect() +} diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs new file mode 100644 index 000000000..0033dcb9d --- /dev/null +++ b/crates/engine/src/design/tests.rs @@ -0,0 +1,863 @@ +//! `design.audit`, `design.fix` and `design.rules`: the checks, the repairs and the report. + +use figcraft_doc::{EffectKind, NodeId, NodeKind, Sizing}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::params::id_of; + +fn ex(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap() +} + +fn id(v: &Value) -> NodeId { + id_of(&v["id"]).unwrap() +} + +fn rules(report: &Value) -> Vec { + report["findings"].as_array().unwrap().iter().filter_map(|f| f["rule"].as_str().map(str::to_string)).collect() +} + +fn has(report: &Value, rule: &str) -> bool { + rules(report).iter().any(|r| r == rule) +} + +fn rule_nodes(report: &Value, rule: &str) -> Vec { + report["findings"].as_array().unwrap().iter().filter(|f| f["rule"] == rule).filter_map(|f| f["node"].as_u64()).collect() +} + +#[test] +fn reports_spacing_radius_copy_and_small_type() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 320, "height": 480, + "props": {"layout": "vertical", "gap": 13, "padding": 11, "cornerRadius": 7}}), + )); + ex(&mut s, "text.create", json!({"text": "Welcome back, Sam!", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 10}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + for rule in ["spacing.off-grid", "radius.off-scale", "copy.exclamation", "type.too-small"] { + assert!(has(&r, rule), "{rule} missing from {r}"); + } + let spacing = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(spacing["suggestion"]["gap"], 12.0, "{r}"); + assert_eq!(spacing["suggestion"]["padding"], json!([12.0, 12.0, 12.0, 12.0]), "{r}"); + assert_eq!(spacing["details"]["gap"], 13.0, "{r}"); + assert_eq!(spacing["details"]["padding"], json!([11.0, 11.0, 11.0, 11.0]), "{r}"); + assert_eq!(spacing["details"]["grid"], 4.0, "{r}"); + assert_eq!(spacing["fixable"], true); +} + +#[test] +fn reports_gradient_text_glow_and_low_contrast() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Ship it", "x": 0, "y": 0}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + let box_id = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 200, "width": 200, "height": 100}))); + ex( + &mut s, + "node.set", + json!({"id": box_id, "props": {"effects": [{"type": "dropShadow", "color": "#00000040", "offset": [0, 0], "radius": 24}]}}), + ); + let white = id(&ex(&mut s, "text.create", json!({"text": "Invisible", "x": 0, "y": 400}))); + ex(&mut s, "node.set", json!({"id": white, "props": {"fill": "#FFFFFF"}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + for rule in ["color.gradient-text", "color.glow", "color.contrast"] { + assert!(has(&r, rule), "{rule} missing from {r}"); + } + let contrast = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "color.contrast").unwrap(); + assert!(contrast["details"]["ratio"].as_f64().is_some_and(|v| v < 4.5), "{r}"); + assert_eq!(contrast["details"]["foreground"], "FFFFFF", "{r}"); +} + +#[test] +fn reports_a_gradient_on_a_shape() { + let mut s = Session::new(); + let rect = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50}))); + ex(&mut s, "node.set", json!({"id": rect, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "color.gradient"), "{r}"); + assert!(!has(&r, "color.gradient-text"), "{r}"); +} + +#[test] +fn counts_type_sizes_and_families_across_the_scope() { + let mut s = Session::new(); + for size in [12, 13, 14, 15, 16, 17, 18, 19] { + ex(&mut s, "text.create", json!({"text": "Text", "x": 0, "y": size as f64 * 20.0, "props": {"fontSize": size}})); + } + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "type.sizes"), "{r}"); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "type.sizes").unwrap(); + assert!(f["message"].as_str().unwrap().contains("8 font sizes"), "{r}"); + assert_eq!(f["details"]["count"], 8, "{r}"); + assert_eq!(f["details"]["sizes"].as_array().map(Vec::len), Some(8), "{r}"); +} + +#[test] +fn selection_scope_ignores_other_layers() { + let mut s = Session::new(); + let bad = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + let good = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 8}}), + )); + s.set_selection(vec![good]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert!(!has(&r, "spacing.off-grid"), "{r}"); + s.set_selection(vec![bad]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert!(has(&r, "spacing.off-grid"), "{r}"); +} + +#[test] +fn a_nested_selection_is_audited_once() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + let child = id(&ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 20, "height": 20}))); + s.set_selection(vec![f, child]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + // The rectangle is only in the report through the frame's subtree. + let rect_findings = r["findings"].as_array().unwrap().iter().filter(|f| f["path"].as_str().unwrap().contains("Rectangle")).count(); + assert!(rect_findings <= 1, "{r}"); +} + +#[test] +fn filters_by_rule_and_severity() { + let mut s = Session::new(); + ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}})); + let only = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + assert_eq!(rules(&only), vec!["spacing.off-grid".to_string()], "{only}"); + assert_eq!(only["byRule"]["spacing.off-grid"], 1, "{only}"); + let high = ex(&mut s, "design.audit", json!({"scope": "page", "minSeverity": "high"})); + assert!(rules(&high).is_empty(), "{high}"); + assert_eq!(high["score"], 100.0, "{high}"); + let all = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(all["score"].as_f64().unwrap() < 100.0, "{all}"); + assert!(all["nodes"].as_u64().unwrap() >= 2, "the report counts the layers it walked: {all}"); +} + +#[test] +fn a_light_border_is_a_hairline() { + let mut s = Session::new(); + let light = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 0, "width": 200, "height": 60, + "props": {"stroke": "#E0E0E0", "strokeWeight": 1} + }), + )); + let strong = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 100, "width": 200, "height": 60, + "props": {"stroke": "#333333", "strokeWeight": 1} + }), + )); + // An inside stroke on a dark panel sits on the panel, not on the page behind it. + let dark_panel = id(&ex( + &mut s, + "node.create", + json!({ + "type": "frame", "x": 0, "y": 200, "width": 200, "height": 60, + "props": {"fill": "#1E1E1E", "stroke": "#2A2A2A", "strokeWeight": 1, "strokeAlign": "inside"} + }), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.border-opacity"]})); + let flagged: Vec = r["findings"].as_array().unwrap().iter().filter_map(|f| f["node"].as_u64()).collect(); + assert!(!flagged.contains(&light.0), "{r}"); + assert!(flagged.contains(&strong.0), "{r}"); + assert!(!flagged.contains(&dark_panel.0), "a dark border on a dark panel is not a strong hairline: {r}"); +} + +#[test] +fn reports_emoji_and_default_names() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + ex(&mut s, "text.create", json!({"text": "Ship it 🚀", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(has(&r, "icon.emoji"), "{r}"); + assert!(has(&r, "naming.auto"), "{r}"); +} + +#[test] +fn lists_the_rules() { + let mut s = Session::new(); + let r = ex(&mut s, "design.rules", json!({})); + let rules = r["rules"].as_array().unwrap(); + assert!(rules.len() >= 15, "{r}"); + let spacing = rules.iter().find(|r| r["id"] == "spacing.off-grid").unwrap(); + assert_eq!(spacing["severity"], "medium"); + assert_eq!(spacing["fixable"], true); + assert_eq!(spacing["presets"], json!(["recommended", "strict"])); + let accents = rules.iter().find(|r| r["id"] == "color.accents").unwrap(); + assert_eq!(accents["presets"], json!(["strict"])); + assert_eq!(r["presets"].as_array().unwrap().len(), 3, "{r}"); +} + +#[test] +fn configure_changes_the_files_design_system() { + let mut s = Session::new(); + let r = ex( + &mut s, + "design.configure", + json!({"preset": "strict", "grid": 8, "radii": [0, 10, 20], "brand": ["#3366FF"], "disabled": ["icon.emoji"]}), + ); + assert_eq!(r["preset"], "strict", "{r}"); + assert_eq!(r["grid"], 8.0, "{r}"); + assert_eq!(r["radii"], json!([0.0, 10.0, 20.0]), "{r}"); + assert_eq!(r["brand"], json!(["#3366FF"]), "{r}"); + assert_eq!(r["disabled"], json!(["icon.emoji"]), "{r}"); + assert_eq!(s.doc().unwrap().design_review.grid(), 8.0); + // The settings are part of the file and undoable with it. + let reset = ex(&mut s, "design.configure", json!({"reset": true})); + assert_eq!(reset["preset"], "recommended", "{reset}"); + assert_eq!(reset["grid"], 4.0, "{reset}"); + assert!(s.doc().unwrap().design_review.is_default()); + assert!(s.execute("design.configure", &json!({"grid": 0})).is_err()); + assert!(s.execute("design.configure", &json!({"radii": ["wide"]})).is_err()); + assert!(s.execute("design.configure", &json!({"disabled": ["no.such.rule"]})).is_err()); +} + +#[test] +fn the_configured_grid_drives_spacing_and_the_fixer() { + let mut s = Session::new(); + ex(&mut s, "design.configure", json!({"grid": 8})); + let on = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "cornerRadius": 8}}), + )); + let off = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 6, "padding": 10, "cornerRadius": 12}}), + )); + let only = json!(["spacing.off-grid", "radius.off-scale"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(!rule_nodes(&r, "spacing.off-grid").contains(&on.0), "{r}"); + assert!(!rule_nodes(&r, "radius.off-scale").contains(&on.0), "{r}"); + assert_eq!(rule_nodes(&r, "spacing.off-grid"), vec![off.0], "{r}"); + assert_eq!(rule_nodes(&r, "radius.off-scale"), vec![off.0], "{r}"); + assert!(r["grid"] == json!(8.0), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let n = s.doc().unwrap().node(off).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 8.0); + assert_eq!(n.layout.as_ref().unwrap().padding, [8.0; 4]); + assert_eq!(n.corners.radii, [16.0; 4]); +} + +#[test] +fn a_custom_radius_scale_is_the_only_scale() { + let mut s = Session::new(); + ex(&mut s, "design.configure", json!({"radii": [10, 20]})); + let ok = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"cornerRadius": 10}}))); + let off = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"cornerRadius": 8}}))); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["radius.off-scale"]})); + assert!(!rule_nodes(&r, "radius.off-scale").contains(&ok.0), "{r}"); + assert_eq!(rule_nodes(&r, "radius.off-scale"), vec![off.0], "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(s.doc().unwrap().node(off).unwrap().corners.radii, [10.0; 4]); +} + +#[test] +fn presets_choose_the_rules_and_disabled_rules_stay_off() { + let mut s = Session::new(); + for (i, fill) in ["#FF0000", "#00AA00", "#0000FF"].iter().enumerate() { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 60, "y": 0, "width": 40, "height": 40, "props": {"fill": fill}})); + } + let stack = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 100, "width": 200, "height": 200}))); + for i in 0..3 { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 20, "y": 0, "width": 10, "height": 10, "parent": stack})); + } + let off_grid = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 100, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + + let recommended = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(recommended["preset"], "recommended", "{recommended}"); + assert!(!has(&recommended, "color.accents"), "{recommended}"); + assert!(!has(&recommended, "layout.no-auto-layout"), "{recommended}"); + let strict = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(has(&strict, "color.accents"), "{strict}"); + assert!(has(&strict, "layout.no-auto-layout"), "{strict}"); + let a11y = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "accessibility"})); + assert!(!has(&a11y, "spacing.off-grid"), "{a11y}"); + + // The file can make Strict its own, and a disabled rule is neither reported nor fixed. + ex(&mut s, "design.configure", json!({"preset": "strict", "disabled": ["spacing.off-grid"]})); + let file = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(file["preset"], "strict", "{file}"); + assert!(has(&file, "color.accents"), "{file}"); + assert!(!has(&file, "spacing.off-grid"), "{file}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(s.doc().unwrap().node(off_grid).unwrap().layout.as_ref().unwrap().gap, 13.0, "a disabled rule is not fixed"); +} + +#[test] +fn contrast_is_checked_in_the_given_variable_modes() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "Theme"})); + ex(&mut s, "variable.addMode", json!({"collection": "Theme", "name": "Dark"})); + ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "surface", "type": "color", "value": "#FFFFFF"})); + ex(&mut s, "variable.set", json!({"variable": "surface", "mode": "Dark", "value": "#222222"})); + ex(&mut s, "variable.create", json!({"collection": "Theme", "name": "ink", "type": "color", "value": "#111111"})); + ex(&mut s, "variable.set", json!({"variable": "ink", "mode": "Dark", "value": "#777777"})); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"fill": "#FFFFFF"}}))); + let t = id(&ex(&mut s, "text.create", json!({"text": "Read me", "x": 10, "y": 10, "parent": f}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "solid", "color": "#111111"}]})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "fill", "variable": "surface"})); + ex(&mut s, "variable.bind", json!({"ids": [t], "field": "fill", "variable": "ink"})); + let only = json!(["color.contrast"]); + let light = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(!has(&light, "color.contrast"), "{light}"); + let dark = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only, "modes": {"Theme": "Dark"}})); + assert!(has(&dark, "color.contrast"), "{dark}"); + assert_eq!(dark["modes"], json!({"Theme": "Dark"}), "{dark}"); + let finding = dark["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "color.contrast").unwrap(); + assert_eq!(finding["fixable"], false, "{dark}"); + assert_eq!(finding["reason"], "modes", "{dark}"); + assert!(finding["message"].as_str().unwrap().contains("Theme: Dark"), "{finding}"); + assert!(s.execute("design.audit", &json!({"scope": "page", "modes": {"Theme": "Dusk"}})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "modes": {"Theme": "Dark"}, "failOn": "high"})).is_err()); +} + +#[test] +fn unfixable_findings_carry_a_reason_code() { + let mut s = Session::new(); + let bound = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 13})); + ex(&mut s, "variable.bind", json!({"ids": [bound], "field": "gap", "variable": "space"})); + let loose = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 300, "y": 0, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 13}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid", "naming.auto"]})); + let findings = r["findings"].as_array().unwrap(); + let bound_f = findings.iter().find(|f| f["node"] == bound.0 && f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(bound_f["fixable"], false, "{r}"); + assert_eq!(bound_f["reason"], "bound", "{r}"); + let loose_f = findings.iter().find(|f| f["node"] == loose.0 && f["rule"] == "spacing.off-grid").unwrap(); + assert_eq!(loose_f["fixable"], true, "{r}"); + assert!(loose_f.get("reason").is_none(), "{r}"); + let named = findings.iter().find(|f| f["rule"] == "naming.auto").unwrap(); + assert_eq!(named["reason"], "decision", "{r}"); +} + +#[test] +fn brand_colours_do_not_count_as_stray_accents() { + let mut s = Session::new(); + for (i, fill) in ["#FF0000", "#00AA00", "#0000FF"].iter().enumerate() { + ex(&mut s, "node.create", json!({"type": "rectangle", "x": i * 60, "y": 0, "width": 40, "height": 40, "props": {"fill": fill}})); + } + let loose = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(has(&loose, "color.accents"), "{loose}"); + let brand = ex(&mut s, "design.configure", json!({"brand": ["#FF0000", "#00AA00"]})); + assert_eq!(brand["brand"], json!(["#FF0000", "#00AA00"]), "{brand}"); + let kept = ex(&mut s, "design.audit", json!({"scope": "page", "preset": "strict"})); + assert!(!has(&kept, "color.accents"), "{kept}"); +} + +#[test] +fn junk_params_are_errors_not_panics() { + let mut s = Session::new(); + for junk in [ + json!({"scope": {"x": 1}}), + json!({"scope": "everything"}), + json!({"rules": [1]}), + json!({"rules": "spacing.off-grid"}), + json!({"rules": ["no.such.rule"]}), + json!({"minSeverity": "loud"}), + ] { + assert!(s.execute("design.audit", &junk).is_err(), "{junk} was accepted"); + } + assert!(s.execute("design.audit", &json!({})).is_ok()); + // Nulls mean "the default", not junk. + assert!(s.execute("design.audit", &json!({"scope": "document", "rules": null, "minSeverity": null})).is_ok()); +} + +fn spaced_frame(s: &mut Session) -> NodeId { + id(&ex( + s, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 13, "padding": 11, "cornerRadius": 7}}), + )) +} + +#[test] +fn fix_snaps_spacing_and_radius_as_one_undo_step() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(r["dryRun"], false, "{r}"); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + assert!(r["byRule"]["spacing.off-grid"].as_u64().unwrap() >= 1, "{r}"); + assert!(r["byRule"]["radius.off-scale"].as_u64().unwrap() >= 1, "{r}"); + { + let n = s.doc().unwrap().node(f).unwrap(); + let al = n.layout.as_ref().unwrap(); + assert_eq!((al.gap, al.padding[0], al.padding[1]), (12.0, 12.0, 12.0)); + assert_eq!(n.corners.uniform(), Some(8.0)); + } + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "spacing.off-grid"), "{after}"); + assert!(!has(&after, "radius.off-scale"), "{after}"); + // The whole repair is one undo step. + ex(&mut s, "edit.undo", json!({})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 13.0); + assert_eq!(n.corners.uniform(), Some(7.0)); +} + +#[test] +fn dry_run_reports_without_changing_anything() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "dryRun": true})); + assert_eq!(r["dryRun"], true, "{r}"); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn fix_filters_by_rule() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["radius.off-scale"]})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.layout.as_ref().unwrap().gap, 13.0, "spacing was not asked for"); + assert_eq!(n.corners.uniform(), Some(8.0)); +} + +#[test] +fn fix_caps_heading_weight_and_removes_tracking() { + let mut s = Session::new(); + let heading = id(&ex(&mut s, "text.create", json!({"text": "Title", "x": 0, "y": 0, "props": {"fontSize": 28, "fontStyle": "Bold"}}))); + let small = id(&ex( + &mut s, + "text.create", + json!({"text": "Label", "x": 0, "y": 60, + "props": {"fontSize": 16, "letterSpacing": {"unit": "pixels", "value": -1.5}}}), + )); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert!(r["changed"].as_u64().unwrap() >= 2, "{r}"); + let doc = s.doc().unwrap(); + let NodeKind::Text(h) = &doc.node(heading).unwrap().kind else { panic!() }; + assert_eq!(h.style.weight(), 600); + let NodeKind::Text(l) = &doc.node(small).unwrap().kind else { panic!() }; + assert_eq!(l.style.letter_spacing.resolve(16.0), 0.0); + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "type.weight"), "{after}"); + assert!(!has(&after, "type.negative-tracking"), "{after}"); +} + +#[test] +fn fix_removes_glows_and_neutralises_coloured_shadows() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + ex( + &mut s, + "node.set", + json!({"id": f, "props": {"effects": [ + {"type": "dropShadow", "color": "#00000040", "offset": [0, 0], "radius": 24}, + {"type": "dropShadow", "color": "#7048E880", "offset": [0, 4], "radius": 12} + ]}}), + ); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + let effects = &s.doc().unwrap().node(f).unwrap().effects; + assert_eq!(effects.len(), 1, "the glow is gone: {effects:?}"); + let EffectKind::DropShadow(shadow) = &effects[0].kind else { panic!() }; + assert_eq!((shadow.color.r, shadow.color.g, shadow.color.b), (0.0, 0.0, 0.0)); + let after = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&after, "color.glow"), "{after}"); + assert!(!has(&after, "color.colored-shadow"), "{after}"); +} + +#[test] +fn fix_leaves_content_and_gradients_alone() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Ship it 🚀!", "x": 0, "y": 0, "props": {"fontSize": 16}}))); + ex(&mut s, "node.set", json!({"id": t, "fills": [{"type": "linearGradient", "stops": ["#ff0000", "#0000ff"]}]})); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let doc = s.doc().unwrap(); + let NodeKind::Text(td) = &doc.node(t).unwrap().kind else { panic!() }; + assert_eq!(td.characters, "Ship it 🚀!"); + assert!(matches!(&td.style.fills.as_deref().unwrap_or(&doc.node(t).unwrap().fills)[0].kind, figcraft_color::PaintKind::Gradient(_))); +} + +#[test] +fn fix_darkens_low_contrast_text() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100}))); + let t = id(&ex(&mut s, "text.create", json!({"text": "Invisible", "x": 0, "y": 0, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + assert!(has(&ex(&mut s, "design.audit", json!({"scope": "page"})), "color.contrast")); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(r["changed"].as_u64().unwrap() >= 1, "{r}"); + { + let doc = s.doc().unwrap(); + let n = doc.node(t).unwrap(); + let NodeKind::Text(td) = &n.kind else { panic!() }; + let paints = td.style.fills.as_deref().unwrap_or(&n.fills); + let color = paints.iter().rev().find_map(|p| p.solid_color()).unwrap(); + assert!(color.contrast(figcraft_color::Color::WHITE) >= 4.5, "{color:?}"); + } + assert!(!has(&ex(&mut s, "design.audit", json!({"scope": "page"})), "color.contrast")); +} + +#[test] +fn reports_text_that_overflows_its_box() { + let mut s = Session::new(); + let t = id(&ex( + &mut s, + "node.create", + json!({"type": "text", "text": "A long headline that needs several lines in a narrow box", + "x": 0, "y": 0, "width": 120, "height": 40, + "props": {"fontSize": 24, "textAutoResize": "none"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + let f = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "layout.text-overflow").unwrap_or_else(|| panic!("{r}")); + assert_eq!(f["node"], t.0, "{r}"); +} + +#[test] +fn a_sibling_background_is_the_text_backdrop() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}})); + let white = + id(&ex(&mut s, "text.create", json!({"text": "White on dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + let dark = + id(&ex(&mut s, "text.create", json!({"text": "Dark on dark", "x": 20, "y": 80, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}))); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + let flagged = rule_nodes(&r, "color.contrast"); + assert!(!flagged.contains(&white.0), "white on the dark sibling is legible: {r}"); + assert!(flagged.contains(&dark.0), "dark on the dark sibling is not: {r}"); +} + +#[test] +fn a_background_inside_a_group_is_found() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + let rect = id(&ex(&mut s, "shape.rectangle", json!({"parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}}))); + s.set_selection(vec![rect]); + ex(&mut s, "object.group", json!({})); + let white = id(&ex( + &mut s, + "text.create", + json!({"text": "White on grouped dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(!rule_nodes(&r, "color.contrast").contains(&white.0), "the grouped background is under the text: {r}"); +} + +#[test] +fn fix_uses_the_sibling_background_for_contrast() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E"}})); + let white = + id(&ex(&mut s, "text.create", json!({"text": "White on dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#FFFFFF"}}))); + let dark = + id(&ex(&mut s, "text.create", json!({"text": "Dark on dark", "x": 20, "y": 80, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}))); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["color.contrast"]})); + let doc = s.doc().unwrap(); + let fill = |id| { + let n = doc.node(id).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!() }; + t.style.fills.as_deref().unwrap_or(&n.fills).iter().rev().find_map(|p| p.solid_color()).unwrap() + }; + let w = fill(white); + assert_eq!((w.r, w.g, w.b), (1.0, 1.0, 1.0), "the legible white text is left alone"); + let d = fill(dark); + assert!(d.contrast(figcraft_color::Color::from_rgb8_const(0x1E, 0x1E, 0x1E)) >= 4.5, "the dark text is lightened: {d:?}"); +} + +#[test] +fn locked_layers_are_left_alone() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "node.set", json!({"id": f, "props": {"locked": true}})); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(!has(&r, "spacing.off-grid") && !has(&r, "radius.off-scale"), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page"})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!((n.layout.as_ref().unwrap().gap, n.corners.uniform()), (13.0, Some(7.0))); +} + +#[test] +fn a_bound_spacing_value_is_reported_but_not_fixed() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "gap", "type": "number", "value": 13})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "gap"})); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap_or_else(|| panic!("{r}")); + assert_eq!(finding["fixable"], false, "{r}"); + assert!(finding["message"].as_str().unwrap().contains("bound"), "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + assert_eq!(s.doc().unwrap().node(f).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn a_padding_binding_owns_the_spacing() { + let mut s = Session::new(); + let f = spaced_frame(&mut s); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 11})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "padding", "variable": "space"})); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "spacing.off-grid").unwrap_or_else(|| panic!("{r}")); + assert_eq!(finding["fixable"], false, "{r}"); + ex(&mut s, "design.fix", json!({"scope": "page", "rules": ["spacing.off-grid"]})); + let n = s.doc().unwrap().node(f).unwrap(); + let al = n.layout.as_ref().unwrap(); + assert_eq!((al.gap, al.padding[0]), (13.0, 11.0), "a padding binding owns the whole layout"); +} + +#[test] +fn a_blended_background_is_not_sampled() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "node.create", json!({"type": "frame", "x": 0, "y": 0, "width": 300, "height": 200, "props": {"fill": "#F4F1EA"}}))); + ex( + &mut s, + "node.create", + json!({"type": "rectangle", "parent": f, "x": 0, "y": 0, "width": 120, "height": 200, "props": {"fill": "#1E1E1E", "blend": "multiply"}}), + ); + let dark = id(&ex( + &mut s, + "text.create", + json!({"text": "Dark on a blended dark", "x": 20, "y": 20, "parent": f, "props": {"fontSize": 16, "fill": "#111111"}}), + )); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.contrast"]})); + assert!(!rule_nodes(&r, "color.contrast").contains(&dark.0), "a blend mode makes the backdrop unknown: {r}"); +} + +#[test] +fn fix_with_ids_leaves_other_layers_alone() { + let mut s = Session::new(); + let a = spaced_frame(&mut s); + let b = spaced_frame(&mut s); + let r = ex(&mut s, "design.fix", json!({"ids": [a]})); + assert_eq!(r["scope"], "selection", "{r}"); + let doc = s.doc().unwrap(); + assert_eq!(doc.node(a).unwrap().layout.as_ref().unwrap().gap, 12.0); + assert_eq!(doc.node(b).unwrap().layout.as_ref().unwrap().gap, 13.0); +} + +#[test] +fn fix_with_exact_leaves_a_child_finding_alone() { + let mut s = Session::new(); + let parent = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Parent", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "cornerRadius": 3}}), + )); + let child = id(&ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Child", "parent": parent, "x": 0, "y": 0, "width": 80, "height": 40, + "props": {"cornerRadius": 3}}), + )); + let r = ex(&mut s, "design.fix", json!({"ids": [parent], "rules": ["radius.off-scale"], "exact": true})); + assert_eq!(r["changed"], 1, "{r}"); + let doc = s.doc().unwrap(); + assert_ne!(doc.node(parent).unwrap().corners.radii[0], 3.0, "the root is repaired"); + assert_eq!(doc.node(child).unwrap().corners.radii[0], 3.0, "an ignored child finding stays: exact means the listed layers only"); +} + +#[test] +fn hardcoded_values_that_match_variables_are_reported() { + let mut s = Session::new(); + ex(&mut s, "variable.createCollection", json!({"name": "C"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "red", "type": "color", "value": "#FF0000"})); + ex(&mut s, "variable.create", json!({"collection": "C", "name": "space", "type": "number", "value": 12})); + let r = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50, "props": {"fill": "#FF0000"}}))); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "x": 0, "y": 100, "width": 200, "height": 100, "props": {"layout": "vertical", "gap": 12}}), + )); + let only_rules = json!(["token.hardcoded-color", "token.hardcoded-number"]); + let before = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only_rules})); + assert!(has(&before, "token.hardcoded-color"), "{before}"); + assert!(has(&before, "token.hardcoded-number"), "{before}"); + ex(&mut s, "variable.bind", json!({"ids": [r], "field": "fill", "variable": "red"})); + ex(&mut s, "variable.bind", json!({"ids": [f], "field": "gap", "variable": "space"})); + let after = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only_rules})); + assert!(rules(&after).is_empty(), "{after}"); +} + +#[test] +fn assert_is_a_ci_gate_on_severity_and_score() { + let mut s = Session::new(); + let _f = spaced_frame(&mut s); + // Off-grid spacing is medium: a high gate passes, a medium gate fails. + assert!(s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).is_ok()); + let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "medium"})).unwrap_err().to_string(); + assert!(err.contains("spacing.off-grid"), "{err}"); + assert!(s.execute("design.assert", &json!({"scope": "page", "minScore": 100})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "minScore": "high"})).is_err()); + assert!(s.execute("design.assert", &json!({"scope": "page", "failOn": "loud"})).is_err()); + // A frame on the grid and the scale has nothing to report. + let mut clean = Session::new(); + ex( + &mut clean, + "node.create", + json!({"type": "frame", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "cornerRadius": 8}}), + ); + let ok = ex(&mut clean, "design.assert", json!({"scope": "page", "failOn": "medium"})); + assert_eq!(ok["ok"], true, "{ok}"); + assert_eq!(ok["score"], 100.0, "{ok}"); +} + +#[test] +fn fix_junk_is_an_error_not_a_panic() { + let mut s = Session::new(); + assert!(s.execute("design.fix", &json!({"scope": "everything"})).is_err()); + assert!(s.execute("design.fix", &json!({"rules": ["no.such.rule"]})).is_err()); + assert!(s.execute("design.fix", &json!({})).is_ok()); +} + +#[test] +fn a_fixed_frame_that_clips_children_is_reported() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Card", "x": 0, "y": 0, "width": 200, "height": 40, + "props": {"layout": "vertical", "gap": 8, "padding": 8, "fill": "#FFFFFF"}}), + )); + ex(&mut s, "text.create", json!({"text": "Row one", "parent": f})); + ex(&mut s, "text.create", json!({"text": "Row two", "parent": f})); + let only = json!(["layout.clipped"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(has(&r, "layout.clipped"), "{r}"); + let finding = r["findings"].as_array().unwrap().iter().find(|f| f["rule"] == "layout.clipped").unwrap(); + assert_eq!(finding["fixable"], false, "{r}"); + assert_eq!(finding["suggestion"]["sizingV"], "hug", "{r}"); + // A frame that hugs grows with its rows, so it cannot clip. + ex(&mut s, "node.set", json!({"id": f, "props": {"sizingV": "hug"}})); + let after = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&after).is_empty(), "{after}"); +} + +#[test] +fn a_plain_clipping_frame_is_not_a_layout_finding() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Crop", "x": 0, "y": 0, "width": 200, "height": 40, + "props": {"fill": "#FFFFFF"}}), + )); + // A manual frame clipping its artwork is a crop, not a layout mistake: `sizingV` cannot fix it. + ex(&mut s, "node.create", json!({"type": "rectangle", "parent": f, "x": 0, "y": 30, "width": 200, "height": 40})); + let only = json!(["layout.clipped"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&r).is_empty(), "clipping a manual frame is intentional: {r}"); +} + +#[test] +fn an_auto_layout_frame_hugs_the_axes_no_size_names() { + let mut s = Session::new(); + let f = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Card", "x": 0, "y": 0, "props": {"layout": "vertical", "gap": 8, "padding": 8}}), + )); + ex(&mut s, "text.create", json!({"text": "Row one", "parent": f})); + ex(&mut s, "text.create", json!({"text": "Row two", "parent": f})); + let n = s.doc().unwrap().node(f).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + assert!(n.height > 40.0 && n.height < 90.0, "hug height fits the rows, got {}", n.height); + // An explicit width stays fixed; the unnamed height hugs. + let g = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Bar", "x": 300, "y": 0, "width": 320, "props": {"layout": "vertical", "gap": 8}}), + )); + let n = s.doc().unwrap().node(g).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); + // No auto layout: the 100×100 defaults stay. + let p = id(&ex(&mut s, "node.create", json!({"type": "frame", "name": "Plain", "x": 700, "y": 0}))); + let n = s.doc().unwrap().node(p).unwrap(); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.width, 100.0); + // A size in props is explicit too: it keeps that axis fixed and the other one hugs. + let q = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Props height", "x": 1000, "y": 0, + "props": {"layout": "vertical", "height": 300}}), + )); + let n = s.doc().unwrap().node(q).unwrap(); + assert_eq!(n.height, 300.0); + assert_eq!(n.child_layout.sizing_v, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_h, Sizing::Hug); + let r = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Props width", "x": 1000, "y": 400, + "props": {"layout": "vertical", "w": 320}}), + )); + let n = s.doc().unwrap().node(r).unwrap(); + assert_eq!(n.width, 320.0); + assert_eq!(n.child_layout.sizing_h, Sizing::Fixed); + assert_eq!(n.child_layout.sizing_v, Sizing::Hug); +} + +#[test] +fn an_icons_stroke_is_not_a_border() { + let mut s = Session::new(); + ex( + &mut s, + "node.create", + json!({"type": "vector", "name": "Chevron", "x": 0, "y": 0, "points": [[0, 0], [8, 8], [0, 16]], + "props": {"stroke": "#6B7280", "strokeWeight": 1.5, "fills": []}}), + ); + let only = json!(["color.border-opacity"]); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(rules(&r).is_empty(), "an icon's stroke is its drawing, not a border: {r}"); + ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Panel", "x": 100, "y": 0, "width": 48, "height": 48, + "props": {"fills": [], "stroke": "#6B7280", "strokeWeight": 1.5}}), + ); + let r = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(has(&r, "color.border-opacity"), "{r}"); +} + +#[test] +fn a_bad_parent_error_names_the_node() { + let mut s = Session::new(); + let t = id(&ex(&mut s, "text.create", json!({"text": "Label", "x": 0, "y": 0}))); + let err = s.execute("node.create", &json!({"type": "rectangle", "parent": t, "x": 0, "y": 0})).unwrap_err().to_string(); + assert!(err.contains("TEXT \"Label\""), "{err}"); + assert!(err.contains("can't contain"), "{err}"); +} diff --git a/crates/engine/src/inspect_fields_tests.rs b/crates/engine/src/inspect_fields_tests.rs index 2083a5108..b7b93fd0d 100644 --- a/crates/engine/src/inspect_fields_tests.rs +++ b/crates/engine/src/inspect_fields_tests.rs @@ -116,6 +116,7 @@ fn empty_options_keep_the_main_tree_and_document_output() { "fontFamily": "Synthetic", "fontSize": 18.0, "fontStyle": "Bold", + "fontWeight": 700, "height": 24.0, "id": 3, "letterSpacing": "1", diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 302e7053e..ca5feaa32 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -16,6 +16,7 @@ mod canvas; pub mod catalog; pub mod cmd; mod content; +mod design; mod dev; pub mod events; mod extensions; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 48d68a901..b2200777a 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -106,6 +106,9 @@ pub struct Prefs { /// files opened or made later start with them. Missing: the toggle's default. #[serde(skip_serializing_if = "BTreeMap::is_empty")] pub view: BTreeMap, + /// Design review ignores, by document path: whole rule ids and `rule@layer` entries. + #[serde(skip_serializing_if = "BTreeMap::is_empty")] + pub design_review_ignored: BTreeMap>, /// The board canvas's background grid (`board.grid`). #[serde(deserialize_with = "crate::board_grid::read")] pub board_grid: crate::board_grid::BoardGrid, @@ -158,6 +161,7 @@ impl Default for Prefs { home_sort: "modified".into(), home_order: "desc".into(), view: BTreeMap::new(), + design_review_ignored: BTreeMap::new(), board_grid: Default::default(), recent_actions: Vec::new(), team_libraries: Vec::new(), diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 59b4ee818..12b74e448 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -18,7 +18,7 @@ pub struct PromptDef { pub defaults: &'static [(&'static str, &'static str)], } -const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text; call screenshot at the end and look at it. Fix anything that is off before finishing, then report the ids of the frames you made."; +const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made."; pub const PROMPTS: &[PromptDef] = &[ PromptDef { @@ -30,7 +30,7 @@ pub const PROMPTS: &[PromptDef] = &[ PromptArg { name: "device", description: "Frame preset (default \"iPhone 16\"; see run_command frame.presets)", required: false }, PromptArg { name: "brand_color", description: "Primary colour (default #3B5BDB)", required: false }, ], - template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [14,24,14,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Bold text inside).\n4. Keep spacing on an 8-point grid and text left-aligned.{verify}", + template: "Design a {screen} screen for a mobile app in FigCraft.\n\n1. run_command frame.create {\"preset\": \"{device}\", \"x\": 0, \"y\": 0, \"name\": \"{screen}\"} and give it a white fill.\n2. set_properties on the frame: {\"layout\": \"vertical\", \"padding\": [64, 24, 32, 24], \"gap\": 16, \"sizingV\": \"fixed\"}.\n3. Add content with create_node using parent = the frame id: a title (text, fontSize 28, fontStyle Semi Bold), supporting text (fontSize 16, colour #555555), inputs or list rows (frames with layout horizontal, padding 16, cornerRadius 12, stroke #E0E0E0, sizingH fill) and a primary button (frame, layout horizontal, mainAlign center, padding [16,24,16,24], cornerRadius 12, fill {brand_color}, sizingH fill, white Semi Bold text inside). Name every layer by what it is.\n4. Keep spacing on an 8-point grid, text left-aligned, and no emoji in the interface.{verify}", defaults: &[("device", "iPhone 16"), ("brand_color", "#3B5BDB")], }, PromptDef { @@ -41,7 +41,7 @@ pub const PROMPTS: &[PromptDef] = &[ PromptArg { name: "name", description: "Design system name (default \"Core\")", required: false }, PromptArg { name: "primary", description: "Primary colour (default #3B5BDB)", required: false }, ], - template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": }; text styles likewise from text layers (Heading 32 Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": } and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}", + template: "Set up the \"{name}\" design system in FigCraft.\n\n1. Variables: run_command variable.createCollection {\"name\": \"{name} colours\", \"modes\": [\"Light\", \"Dark\"]}, then variable.create for color/bg, color/fg and color/primary with values per mode ({\"values\": {\"Light\": …, \"Dark\": …}}); primary is {primary} in Light.\n2. Paint styles: create a swatch rectangle per colour and run style.create {\"type\": \"paint\", \"name\": \"{name}/Primary\", \"from\": }; text styles likewise from text layers (Heading 32 Semi Bold, Body 16 Regular, Caption 12).\n3. Button component: a frame with auto layout (horizontal, padding [12,20,12,20], cornerRadius 8, mainAlign center) containing a text \"Button\"; style.apply the primary paint style; component.create on it. Make a secondary variant (duplicate, outline style), then component.combineVariants on both.\n4. Bind the button fill to color/primary with variable.bind {\"ids\": [..], \"field\": \"fill\", \"variable\": } and check both modes by variable.setMode on a frame.\n5. list_commands with filter \"style\" or \"variable\" shows the exact params.{verify}", defaults: &[("name", "Core"), ("primary", "#3B5BDB")], }, PromptDef { @@ -51,10 +51,18 @@ pub const PROMPTS: &[PromptDef] = &[ args: &[ PromptArg { name: "product", description: "What the page sells", required: true }, PromptArg { name: "width", description: "Page width (default 1440)", required: false }, - PromptArg { name: "accent", description: "Accent colour (default #7048E8)", required: false }, + PromptArg { name: "accent", description: "Accent colour (default #2563EB)", required: false }, ], - template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Bold headline, an 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft dropShadow effect, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text).\n3. Use batch to apply repeated styling to several ids in one undo step.\n4. Finish with sizingV hug on the page frame so it fits its content.{verify}", - defaults: &[("width", "1440"), ("accent", "#7048E8")], + template: "Design a landing page for {product} in FigCraft.\n\n1. create_node a frame {\"type\": \"frame\", \"x\": 0, \"y\": 0, \"width\": {width}, \"height\": 2400, \"name\": \"Landing\", \"props\": {\"fill\": \"#FFFFFF\", \"layout\": \"vertical\", \"gap\": 0}}.\n2. Sections are child frames with sizingH fill and their own auto layout: Nav (horizontal, spaceBetween, padding [20,80,20,80]); Hero (vertical, center, padding 120, gap 24: a 64px Semi Bold headline, a 20px subhead, a CTA button filled {accent}); Features (horizontal, gap 32, padding 80: three cards with cornerRadius 16, padding 32, a soft neutral dropShadow, title + body text, each sizingH fill); CTA band filled {accent} with white text; Footer (padding 40, small grey text, no lower than #6B7280).\n3. Name every layer by what it is. Use one accent, one neutral ramp and at most three text colours; no emoji, gradient text or glows.\n4. Use batch to apply repeated styling to several ids in one undo step.\n5. Finish with sizingV hug on the page frame so it fits its content.{verify}", + defaults: &[("width", "1440"), ("accent", "#2563EB")], + }, + PromptDef { + name: "design_review", + title: "Review a design", + description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.", + args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }], + template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}\n6. Take a screenshot of the frame you changed and look at it.", + defaults: &[("target", "page")], }, PromptDef { name: "prototype_flow", diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 70ac05999..78be68cec 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -42,8 +42,12 @@ screenshot returns a PNG of the page or of given layers to look at. undo/redo st Comments: comment.list returns threads (text, anchor node id, frame, page, x/y, replies); fix open ones, \ reply with what changed, then resolve (a reply reopens a thread). To react to new feedback, call \ wait_for_changes {after, timeoutMs} and pass the returned cursor back. \ +Design review: design.audit {scope} reports spacing, radii, type, colour, contrast, copy and naming findings \ +with severities; design.fix repairs the fixable ones as one undo step; design.rules lists the rules and \ +presets; design.configure {preset, grid, radii, brand, disabled} sets the file's design system, and \ +design.assert {failOn, minScore} is a read-only CI gate. \ Resources: figcraft://document, figcraft://node/{id}, figcraft://command/{id}, figcraft://comments. \ -prompts/list has workflows, including fix_comments."; +prompts/list has workflows, including fix_comments and design_review."; /// An MCP server bound to one backend. pub struct Server { diff --git a/crates/mcp/tests/it/protocol.rs b/crates/mcp/tests/it/protocol.rs index cadadbad0..1e83e5646 100644 --- a/crates/mcp/tests/it/protocol.rs +++ b/crates/mcp/tests/it/protocol.rs @@ -219,13 +219,16 @@ fn prompts_list_and_get() { let mut c = Client::new(); let r = c.rpc("prompts/list", json!({})); let names: Vec<&str> = r["result"]["prompts"].as_array().unwrap().iter().map(|p| p["name"].as_str().unwrap()).collect(); - assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "prototype_flow", "fix_comments", "watch_comments"]); + assert_eq!(names, ["mobile_screen", "design_system", "landing_page", "design_review", "prototype_flow", "fix_comments", "watch_comments"]); let r = c.rpc("prompts/get", json!({"name": "mobile_screen", "arguments": {"screen": "login"}})); let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); assert!(text.contains("login") && text.contains("iPhone 16") && text.contains("#3B5BDB") && !text.contains("{device}")); assert_eq!(c.rpc("prompts/get", json!({"name": "mobile_screen"}))["error"]["code"], -32602); assert_eq!(c.rpc("prompts/get", json!({"name": "nope"}))["error"]["code"], -32602); assert_eq!(c.rpc("prompts/get", json!({"name": "landing_page", "arguments": {"product": ["x"]}}))["error"]["code"], -32602); + let r = c.rpc("prompts/get", json!({"name": "design_review", "arguments": {"target": "document"}})); + let text = r["result"]["messages"][0]["content"]["text"].as_str().unwrap(); + assert!(text.contains("design.audit") && text.contains("\"document\"") && !text.contains("{target}"), "{text}"); let r = c.rpc("prompts/get", json!({"name": "prototype_flow"})); assert!(r["result"]["messages"][0]["content"]["text"].as_str().unwrap().contains("Home, Details, Checkout")); let r = c.rpc("prompts/get", json!({"name": "fix_comments", "arguments": {"auto_resolve": "no", "author": "Ada"}})); From c0811b772b7573e772509c9643ebeb03bf84b676 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:57:32 +0800 Subject: [PATCH 02/57] M13: address the engine review findings --- crates/collab/src/change.rs | 5 ++++ crates/collab/src/diff_tests.rs | 14 ++++++++++- crates/collab/src/docprops.rs | 1 + crates/engine/src/cmd/create.rs | 2 +- crates/engine/src/design/fix.rs | 9 ++++--- crates/engine/src/design/mod.rs | 31 +++++++++++++++++------- crates/engine/src/design/tests.rs | 39 +++++++++++++++++++++++++++++++ crates/mcp/src/prompts.rs | 4 ++-- docs/collab-protocol.md | 3 ++- 9 files changed, 90 insertions(+), 18 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 442376f37..e7ecf85f4 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -229,6 +229,11 @@ pub enum DocProp { Vote, /// Ended votes' results kept in the file, oldest first (whole). VoteHistory, + /// The file's design review settings (`design.configure`). + /// + /// Kept last: the wire encodes a variant's position, so adding one before it would shift the + /// existing properties. + DesignReview, } /// A document-level entry, by id. diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index bb81d0b1b..9c252c3e9 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::sync::Arc; use figcraft_color::{Color, Paint}; -use figcraft_doc::{Comment, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; +use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; use crate::replica::{Mode, Replica}; @@ -48,6 +48,18 @@ fn property_edits_send_only_what_changed() { assert!(round_trip(&a, a.document()).is_empty(), "nothing changed"); } +#[test] +fn design_review_settings_round_trip_and_reach_a_snapshot() { + let (a, _, _, _) = setup(); + let mut b = a.document().clone(); + b.design_review.preset = DesignPreset::Strict; + b.design_review.grid = 8.0; + let changes = round_trip(&a, &b); + assert!(changes.contains(&Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() })); + let snapshot = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + assert!(snapshot.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "a snapshot carries the review settings"); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index b590064df..9a1305c62 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -353,6 +353,7 @@ doc_scalars! { Timer => timer, Vote => vote, VoteHistory => vote_history, + DesignReview => design_review, } /// Keyed maps (no order): changed and added entries are put, missing ones removed. diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 920ec1113..5d23d6d02 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -99,7 +99,7 @@ pub fn specs() -> Vec { spec!( "text.create", "Text", - "{text | characters, x?, y? (ignored inside an auto layout parent), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", + "{text | characters, x?, y? (ignored inside an auto layout parent unless props.absolute is true, which keeps the transform they set), parent?, index?, name? (default: the first line), width? (fixed width wraps), props? (fontSize, fontWeight, fontFamily, …), select? (default true)}", true, |s, p| { create_kind(s, p, "text") } ), diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index e6a5e6d7e..ca110cca7 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -13,9 +13,8 @@ use serde_json::{Value, json}; use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; -/// Fix what `roots` made fixable among `filter`'s rules. With `exact`, only findings on the roots -/// themselves are repaired, not findings on their descendants. `dry_run` reports the same counts -/// without changing the document. +/// Fix what `roots` made fixable among `filter`'s rules. With `exact_ids`, only findings on those +/// layers are repaired, not findings on their descendants. pub(crate) fn run( doc: &mut Document, roots: &[NodeId], @@ -24,7 +23,7 @@ pub(crate) fn run( scope: &str, preset: Option, filter: Option<&BTreeSet>, - exact: bool, + exact_ids: Option<&[NodeId]>, dry_run: bool, ) -> Value { let settings = Settings::new(doc, preset); @@ -34,7 +33,7 @@ pub(crate) fn run( .iter() .filter(|f| f.fixable && settings.enabled(f.rule)) .filter(|f| filter.is_none_or(|set| set.contains(f.rule))) - .filter(|f| !exact || roots.contains(&f.node)) + .filter(|f| exact_ids.is_none_or(|ids| ids.contains(&f.node))) .map(|f| (f.node, f.rule)) .collect(); let mut by_rule: BTreeMap<&'static str, usize> = BTreeMap::new(); diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 7e8229323..ec3fb1611 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -91,8 +91,16 @@ fn fix_cmd(s: &mut Session, p: &Value) -> Result { let filter = filter_arg("design.fix", p)?; let preset = preset_arg("design.fix", p)?; let exact = params::boolean(p, "exact").unwrap_or(false); + let exact_ids = if exact { ids_arg("design.fix", p)? } else { None }; let dry = params::boolean(p, "dryRun").unwrap_or(false); - Ok(fix::run(s.doc_mut()?, &roots, anchor, &path, &label, preset, filter.as_ref(), exact, dry)) + // A dry run or a fix that changes nothing must not mark the file unsaved or add an undo step: + // work on a copy and put it back only when it differs. + let mut doc = s.doc()?.clone(); + let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), dry); + if !dry && s.doc()? != &doc { + *s.doc_mut()? = doc; + } + Ok(result) } /// `design.assert`: a read-only gate for CI. Returns the score when the design passes; an error @@ -267,16 +275,23 @@ fn settings_json(config: &DesignReview) -> Value { /// The layers a command works on, its scope label, the layer aggregate findings point at and that /// layer's path. +/// The `ids` parameter, parsed without collapsing ancestors: `exact` needs the layers the caller +/// listed, while the walk uses their top-most roots. +fn ids_arg(cmd: &str, p: &Value) -> Result>> { + let Some(v) = params::get(p, "ids") else { return Ok(None) }; + let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + let mut ids = Vec::new(); + for item in items { + let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; + ids.push(id); + } + Ok(Some(ids)) +} + fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { let doc = s.doc()?; // `ids` names the layers directly (the review window fixes only the findings the user kept). - if let Some(v) = params::get(p, "ids") { - let Value::Array(items) = v else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; - let mut ids = Vec::new(); - for item in items { - let Some(id) = params::id_of(item) else { return Err(bad(cmd, "`ids` must be an array of layer ids")) }; - ids.push(id); - } + if let Some(ids) = ids_arg(cmd, p)? { let roots = top_most(doc, &ids); let anchor = roots.first().copied(); let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 0033dcb9d..7984e305d 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -687,6 +687,45 @@ fn fix_with_exact_leaves_a_child_finding_alone() { assert_eq!(doc.node(child).unwrap().corners.radii[0], 3.0, "an ignored child finding stays: exact means the listed layers only"); } +#[test] +fn fix_with_exact_repairs_a_listed_parent_and_child() { + let mut s = Session::new(); + let parent = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Parent", "x": 0, "y": 0, "width": 200, "height": 100, + "props": {"layout": "vertical", "cornerRadius": 3}}), + )); + let child = id(&ex( + &mut s, + "node.create", + json!({"type": "rectangle", "name": "Child", "parent": parent, "x": 0, "y": 0, "width": 80, "height": 40, + "props": {"cornerRadius": 3}}), + )); + let r = ex(&mut s, "design.fix", json!({"ids": [parent, child], "rules": ["radius.off-scale"], "exact": true})); + assert_eq!(r["changed"], 2, "{r}"); + let doc = s.doc().unwrap(); + assert_ne!(doc.node(parent).unwrap().corners.radii[0], 3.0, "the root is repaired"); + assert_ne!(doc.node(child).unwrap().corners.radii[0], 3.0, "a listed child is repaired too"); +} + +#[test] +fn fix_dry_run_and_no_op_do_not_dirty_the_document() { + let mut s = Session::new(); + let undo = s.ds().unwrap().history.undo.len(); + let redo = s.ds().unwrap().history.redo.len(); + let r = ex(&mut s, "design.fix", json!({"scope": "page", "dryRun": true})); + assert_eq!(r["changed"], 0, "{r}"); + assert_eq!(s.ds().unwrap().history.undo.len(), undo, "a dry run adds no undo step"); + assert_eq!(s.ds().unwrap().history.redo.len(), redo, "a dry run keeps redo"); + assert!(!s.ds().unwrap().is_dirty(), "a dry run leaves the file saved"); + let r = ex(&mut s, "design.fix", json!({"scope": "page"})); + assert_eq!(r["changed"], 0, "{r}"); + assert_eq!(s.ds().unwrap().history.undo.len(), undo, "a no-op fix adds no undo step"); + assert_eq!(s.ds().unwrap().history.redo.len(), redo, "a no-op fix keeps redo"); + assert!(!s.ds().unwrap().is_dirty(), "a no-op fix leaves the file saved"); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); diff --git a/crates/mcp/src/prompts.rs b/crates/mcp/src/prompts.rs index 12b74e448..287470d78 100644 --- a/crates/mcp/src/prompts.rs +++ b/crates/mcp/src/prompts.rs @@ -18,7 +18,7 @@ pub struct PromptDef { pub defaults: &'static [(&'static str, &'static str)], } -const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made."; +const VERIFY: &str = "\n\nVerify as you go: after each major step call inspect_document (or get_node on the frame) and check sizes, fills, layout and text. Before finishing, run design.audit on the target you were asked to change — the requested selection or page, or the frames you created — not the rest of the document, and fix every high finding you are permitted to repair, running it again until none are left (run_command design.rules lists the checks). Call screenshot at the end and look at it. Fix anything that is off, then report the ids of the frames you made or changed."; pub const PROMPTS: &[PromptDef] = &[ PromptDef { @@ -61,7 +61,7 @@ pub const PROMPTS: &[PromptDef] = &[ title: "Review a design", description: "Audit the selection, page or document for the usual AI-generated UI tells, fix the mechanical ones, then use judgment for copy, naming, gradients and overflow; re-audit and report what a person still has to decide.", args: &[PromptArg { name: "target", description: "selection, page or document (default page)", required: false }], - template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}\n6. Take a screenshot of the frame you changed and look at it.", + template: "Review and finish the design in this FigCraft document.\n\n1. Read the screen first with inspect_document and note the product and audience from its text. Write a five-line direction before editing: product (one plain sentence), character (two or three concrete words, never clean/modern/minimal), world (the material or place it belongs to), moments (one or two places for colour, material and detail), signature (one small recurring detail). Do not change what the product is, its features or its section order, and keep every claim true.\n2. Run run_command {\"command\": \"design.audit\", \"params\": {\"scope\": \"{target}\"}}. `design.rules` lists the checks.\n3. Repair what arithmetic can: run run_command {\"command\": \"design.fix\", \"params\": {\"scope\": \"{target}\"}} (one undo step), then audit again. A finding marked `fixable: false`, or one whose message says it is bound to a style or variable, belongs to the design system: leave it and name it in the report.\n4. Handle what the audit cannot, worst first, with the smallest edit and one batch per area: rewrite exclamation, hype and greeting copy into specific product copy; name default layers by what they are; replace hue gradients and gradient text with a solid from the direction unless the brand owns them; resize or reflow a box whose text overflows. If the whole screen is generic, change spacing, type and one moment of colour or material — not the structure. Do not invent features, data or claims.\n5. Run design.audit again until no high findings are left that steps 3 and 4 can repair. Stop when no permitted repair remains. Report the score and counts before and after, the direction, what you fixed mechanically, what you fixed by judgment, and every finding you left with its reason.{verify}", defaults: &[("target", "page")], }, PromptDef { diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 41c73190d..1a7e77052 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -148,7 +148,8 @@ As built: A diff gives new keys only to the children that need them (the longest run of old keys that is still increasing keeps its keys) and re-spaces a parent whose keys would grow past 48 characters. - **Document-level objects covered now**: the file name, the current page, document colours, the - colour profile, image presets, annotation categories and library data (whole values); styles, + colour profile, image presets, annotation categories, the design review settings + (`DocProp::DesignReview`) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content hash, the encoded bytes as base64; as an entry applies the claim is checked: every key is From 9beff066520756432f39d2809177517a95572e15 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 08:11:55 +0800 Subject: [PATCH 03/57] M13: a truncated audit never passes the CI gate --- crates/engine/src/design/mod.rs | 11 ++++++++++- crates/engine/src/design/tests.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index ec3fb1611..3dc4d261c 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -44,7 +44,7 @@ pub fn specs() -> Vec { spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists or the score is below minScore; read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated by the node cap (what it did not reach is unchecked: narrow the scope or filter the rules); read-only, for CI", false, assert_cmd ), @@ -126,6 +126,15 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) .unwrap_or_default(); let score = report["score"].as_f64().unwrap_or(0.0); + // A truncated audit checked only the first nodes of the scope: what it did not reach is + // unchecked, so it can never prove a design passes (a white-on-white label past the cap + // would sail through as score 100). + if report["truncated"].as_bool() == Some(true) { + let nodes = report["nodes"].as_u64().unwrap_or(0); + return Err(EngineError::Other(format!( + "design review failed: the audit stopped at the node cap after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or filter the rules, then assert again" + ))); + } if !failing.is_empty() || score < min_score { let mut by_rule: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); for f in &failing { diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 7984e305d..075210ce5 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -726,6 +726,34 @@ fn fix_dry_run_and_no_op_do_not_dirty_the_document() { assert!(!s.ds().unwrap().is_dirty(), "a no-op fix leaves the file saved"); } +#[test] +fn assert_fails_when_the_audit_is_truncated() { + let mut s = Session::new(); + // The audit stops at the 50,000-node cap, so the badge at the end is never reached: white + // text in a white frame, a contrast failure the truncated report cannot see. + let page = s.page().unwrap(); + { + let doc = s.doc_mut().unwrap(); + for i in 0..50_100 { + doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + } + } + let holder = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Badge holder", "x": 0.0, "y": 0.0, "width": 40.0, "height": 24.0, "props": {"fill": "#FFFFFF"}}), + )); + let badge = id(&ex(&mut s, "text.create", json!({"text": "0", "name": "Badge", "parent": holder, "props": {"fill": "#FFFFFF"}}))); + // Auditing the badge alone reports it: the cap is what hides it, not innocence. + let r = ex(&mut s, "design.audit", json!({"ids": [badge], "rules": ["color.contrast"]})); + assert!(has(&r, "color.contrast"), "{r}"); + let r = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert_eq!(r["truncated"], true, "{r}"); + // The gate must not turn a truncated audit into a pass at score 100. + let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).unwrap_err().to_string(); + assert!(err.contains("node cap"), "{err}"); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); From b60cdfcba66d72ca1dd31f16a297980d705420b1 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:31:35 +0800 Subject: [PATCH 04/57] M13: the audit's node limit is a parameter --- crates/engine/src/design/audit.rs | 30 +++++++++++++++++----- crates/engine/src/design/fix.rs | 7 +++--- crates/engine/src/design/mod.rs | 28 +++++++++++++++------ crates/engine/src/design/tests.rs | 41 ++++++++++++++++++++++++++++++- 4 files changed, 89 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 0a39840e5..42a53767a 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -17,8 +17,11 @@ use crate::cmd::lists::paint_binding_key; use super::rules::{Severity, rule}; -/// Most layers one audit looks at; past it the report says `truncated`. -const MAX_NODES: usize = 50_000; +/// Most layers one audit looks at; past it the report says `truncated`. A call may raise it with +/// `limit` (a CI gate over a huge file), but never past [`MAX_LIMIT`]. +pub(crate) const MAX_NODES: usize = 50_000; +/// The most nodes one audit may be asked to look at, so a typo cannot stall a machine for minutes. +pub(crate) const MAX_LIMIT: usize = 1_000_000; /// Most text layers one audit lays out for the overflow check (text layout is the expensive part). const MAX_TEXT_MEASURED: usize = 2_000; /// Most auto layout frames one audit measures for clipped children (bounds are per-subtree). @@ -186,6 +189,8 @@ pub(crate) struct Report { pub(crate) findings: Vec, pub(crate) nodes: usize, pub(crate) truncated: bool, + /// The node cap this report was collected under (`limit`). + pub(crate) limit: usize, } /// A colour token's default-mode value, for the hardcoded-value check. @@ -265,11 +270,21 @@ struct Ctx<'a> { /// Distinct accent colours, with the first layer that paints each (for `color.accents`). accents: BTreeMap<[u8; 4], String>, truncated: bool, + /// The node cap this run stops at. + max_nodes: usize, } /// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the /// ones marked fixable. -pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, anchor_path: &str, scope: &str, settings: &Settings) -> Report { +pub(crate) fn collect( + doc: &Document, + roots: &[NodeId], + anchor: Option, + anchor_path: &str, + scope: &str, + settings: &Settings, + max_nodes: usize, +) -> Report { let mut ctx = Ctx { doc, findings: Vec::new(), @@ -284,12 +299,13 @@ pub(crate) fn collect(doc: &Document, roots: &[NodeId], anchor: Option, settings: settings.clone(), accents: BTreeMap::new(), truncated: false, + max_nodes, }; for root in roots { ctx.walk(*root); } ctx.scope_rules(anchor, anchor_path, scope); - Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated } + Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated, limit: max_nodes } } /// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings @@ -304,9 +320,10 @@ pub(crate) fn run( filter: Option<&BTreeSet>, preset: Option, modes: BTreeMap, + max_nodes: usize, ) -> Value { let settings = Settings::new(doc, preset).in_modes(doc, modes); - let report = collect(doc, roots, anchor, anchor_path, scope, &settings); + let report = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); let shown: Vec<&Finding> = report .findings .iter() @@ -330,6 +347,7 @@ pub(crate) fn run( o.insert("counts".into(), json!({"high": counts[2], "medium": counts[1], "low": counts[0]})); o.insert("byRule".into(), json!(by_rule)); o.insert("nodes".into(), json!(report.nodes)); + o.insert("limit".into(), json!(report.limit)); o.insert("findings".into(), json!(findings)); o.insert("truncated".into(), json!(report.truncated)); } @@ -340,7 +358,7 @@ impl Ctx<'_> { fn walk(&mut self, root: NodeId) { let mut stack = vec![(root, String::new())]; while let Some((id, parent)) = stack.pop() { - if self.visited >= MAX_NODES { + if self.visited >= self.max_nodes { self.truncated = true; return; } diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index ca110cca7..891e23bd4 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -14,7 +14,7 @@ use serde_json::{Value, json}; use super::audit::{Report, Settings, backdrop, collect, is_colored_shadow, is_glow, text_color}; /// Fix what `roots` made fixable among `filter`'s rules. With `exact_ids`, only findings on those -/// layers are repaired, not findings on their descendants. +/// layers are repaired, not findings on their descendants. The walk stops at `max_nodes` nodes. pub(crate) fn run( doc: &mut Document, roots: &[NodeId], @@ -24,10 +24,11 @@ pub(crate) fn run( preset: Option, filter: Option<&BTreeSet>, exact_ids: Option<&[NodeId]>, + max_nodes: usize, dry_run: bool, ) -> Value { let settings = Settings::new(doc, preset); - let before = collect(doc, roots, anchor, anchor_path, scope, &settings); + let before = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); let targets: Vec<(NodeId, &'static str)> = before .findings .iter() @@ -55,7 +56,7 @@ pub(crate) fn run( } } } - let after = collect(doc, roots, anchor, anchor_path, scope, &settings); + let after = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); json!({ "scope": scope, "dryRun": dry_run, diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 3dc4d261c..03a8bfe59 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -30,21 +30,21 @@ pub fn specs() -> Vec { spec!( "design.audit", "Check design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", false, audit_cmd ), spec!( "design.fix", "Fix design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), exact?: bool (with ids: repair only findings on those layers, not their descendants), limit?: 1000-1000000 (nodes the walk looks at; default 50000), dryRun?: bool (default false)} → {scope, dryRun, changed, skipped, byRule, before: {score, counts, nodes, findings}, after: {score, counts, nodes, findings}} repairs the findings marked fixable in one undo step; content, naming and gradients are left alone", true, fix_cmd ), spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated by the node cap (what it did not reach is unchecked: narrow the scope or filter the rules); read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated at the node limit it ran with (what it did not reach is unchecked: narrow the scope, filter the rules or raise `limit`); read-only, for CI", false, assert_cmd ), @@ -83,7 +83,8 @@ fn audit_cmd(s: &mut Session, p: &Value) -> Result { let filter = filter_arg("design.audit", p)?; let preset = preset_arg("design.audit", p)?; let modes = modes_arg("design.audit", p, s.doc()?)?; - Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes)) + let limit = limit_arg("design.audit", p)?; + Ok(audit::run(s.doc()?, &roots, &label, anchor, &path, min, filter.as_ref(), preset, modes, limit)) } fn fix_cmd(s: &mut Session, p: &Value) -> Result { @@ -92,11 +93,12 @@ fn fix_cmd(s: &mut Session, p: &Value) -> Result { let preset = preset_arg("design.fix", p)?; let exact = params::boolean(p, "exact").unwrap_or(false); let exact_ids = if exact { ids_arg("design.fix", p)? } else { None }; + let limit = limit_arg("design.fix", p)?; let dry = params::boolean(p, "dryRun").unwrap_or(false); // A dry run or a fix that changes nothing must not mark the file unsaved or add an undo step: // work on a copy and put it back only when it differs. let mut doc = s.doc()?.clone(); - let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), dry); + let result = fix::run(&mut doc, &roots, anchor, &path, &label, preset, filter.as_ref(), exact_ids.as_deref(), limit, dry); if !dry && s.doc()? != &doc { *s.doc_mut()? = doc; } @@ -120,7 +122,8 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { }; // The score covers the whole review (as the window shows it); only findings at or above // `failOn` fail the gate. - let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes); + let limit = limit_arg("design.assert", p)?; + let report = audit::run(s.doc()?, &roots, &label, anchor, &path, Severity::Low, filter.as_ref(), preset, modes, limit); let failing: Vec<&Value> = report["findings"] .as_array() .map(|v| v.iter().filter(|f| f["severity"].as_str().and_then(Severity::from_id).is_some_and(|s| s >= fail_on)).collect()) @@ -132,7 +135,7 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { if report["truncated"].as_bool() == Some(true) { let nodes = report["nodes"].as_u64().unwrap_or(0); return Err(EngineError::Other(format!( - "design review failed: the audit stopped at the node cap after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or filter the rules, then assert again" + "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids), filter the rules, or raise `limit`, then assert again" ))); } if !failing.is_empty() || score < min_score { @@ -160,6 +163,17 @@ fn severity_named(cmd: &str, p: &Value, key: &str, default: Severity) -> Result< } } +/// The `limit` parameter: how many nodes one audit walk may look at before the report says +/// `truncated`. Default 50,000; a CI gate over a huge file may raise it, never past the hard cap. +fn limit_arg(cmd: &str, p: &Value) -> Result { + let Some(v) = params::get(p, "limit") else { return Ok(audit::MAX_NODES) }; + let Some(n) = params::f64_of(v) else { return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000")) }; + if !n.is_finite() || n.fract() != 0.0 || !(1_000.0..=(audit::MAX_LIMIT as f64)).contains(&n) { + return Err(bad(cmd, "`limit` must be a whole number of nodes between 1,000 and 1,000,000")); + } + Ok(n as usize) +} + fn preset_arg(cmd: &str, p: &Value) -> Result> { match params::string(p, "preset").map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) { None => Ok(None), diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 075210ce5..61145f215 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -749,9 +749,48 @@ fn assert_fails_when_the_audit_is_truncated() { assert!(has(&r, "color.contrast"), "{r}"); let r = ex(&mut s, "design.audit", json!({"scope": "page"})); assert_eq!(r["truncated"], true, "{r}"); + assert_eq!(r["limit"], 50_000, "{r}"); // The gate must not turn a truncated audit into a pass at score 100. let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).unwrap_err().to_string(); - assert!(err.contains("node cap"), "{err}"); + assert!(err.contains("stopped at the 50000-node limit"), "{err}"); +} + +#[test] +fn a_raised_limit_lets_a_huge_page_finish_and_assert_for_real() { + let mut s = Session::new(); + let page = s.page().unwrap(); + { + let doc = s.doc_mut().unwrap(); + for i in 0..50_100 { + doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + } + } + let holder = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Badge holder", "x": 0.0, "y": 0.0, "width": 40.0, "height": 24.0, "props": {"fill": "#FFFFFF"}}), + )); + ex(&mut s, "text.create", json!({"text": "0", "name": "Badge", "parent": holder, "props": {"fill": "#FFFFFF"}})); + // With the limit raised, the same page finishes: the audit is not truncated and reports the + // badge's real contrast failure, so the gate fails on the finding, not on the cap. + let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 60_000, "rules": ["color.contrast"]})); + assert_eq!(r["truncated"], false, "{r}"); + assert_eq!(r["limit"], 60_000, "{r}"); + assert!(has(&r, "color.contrast"), "{r}"); + let err = s.execute("design.assert", &json!({"scope": "page", "limit": 60_000, "failOn": "high"})).unwrap_err().to_string(); + assert!(err.contains("color.contrast"), "{err}"); +} + +#[test] +fn a_bad_limit_is_an_error() { + let mut s = Session::new(); + for limit in [json!(999), json!(1_000_001), json!(5.5), json!("many")] { + let err = s.execute("design.audit", &json!({"scope": "page", "limit": limit})).unwrap_err().to_string(); + assert!(err.contains("`limit` must be a whole number of nodes between 1,000 and 1,000,000"), "{err}"); + } + // The bounds themselves are accepted. + let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 1_000})); + assert_eq!(r["limit"], 1_000, "{r}"); } #[test] From 569471dd70bd56d27708a1ce31ef99837579c397 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 10:43:23 +0800 Subject: [PATCH 05/57] M13: the review says what it did not check --- crates/engine/src/design/audit.rs | 55 +++++++++++++++---- crates/engine/src/design/fix.rs | 15 ++++++ crates/engine/src/design/mod.rs | 24 ++++++++- crates/engine/src/design/tests.rs | 88 +++++++++++++++++++++++++++++++ 4 files changed, 170 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 42a53767a..ff7e1fbae 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -191,6 +191,11 @@ pub(crate) struct Report { pub(crate) truncated: bool, /// The node cap this report was collected under (`limit`). pub(crate) limit: usize, + /// How many text layers the walk saw past the overflow-measure cap. They were counted but not + /// measured, so an assertion on `layout.text-overflow` cannot prove a pass. + pub(crate) text_unmeasured: usize, + /// How many clip-holding frames the walk saw past the clipping-measure cap, likewise. + pub(crate) frames_unmeasured: usize, } /// A colour token's default-mode value, for the hardcoded-value check. @@ -272,6 +277,10 @@ struct Ctx<'a> { truncated: bool, /// The node cap this run stops at. max_nodes: usize, + /// Text layers seen past the overflow-measure cap. + text_unmeasured: usize, + /// Clip-holding frames seen past the clipping-measure cap. + frames_unmeasured: usize, } /// Walk `roots` and collect every finding. `design.audit` reports them; `design.fix` acts on the @@ -300,12 +309,21 @@ pub(crate) fn collect( accents: BTreeMap::new(), truncated: false, max_nodes, + text_unmeasured: 0, + frames_unmeasured: 0, }; for root in roots { ctx.walk(*root); } ctx.scope_rules(anchor, anchor_path, scope); - Report { findings: ctx.findings, nodes: ctx.visited, truncated: ctx.truncated, limit: max_nodes } + Report { + findings: ctx.findings, + nodes: ctx.visited, + truncated: ctx.truncated, + limit: max_nodes, + text_unmeasured: ctx.text_unmeasured, + frames_unmeasured: ctx.frames_unmeasured, + } } /// Audit `roots` (pages, frames or layers), labelled `scope` in the report. Aggregate findings @@ -350,6 +368,13 @@ pub(crate) fn run( o.insert("limit".into(), json!(report.limit)); o.insert("findings".into(), json!(findings)); o.insert("truncated".into(), json!(report.truncated)); + // Checks the walk capped before finishing: what they did not measure is unchecked. + if report.text_unmeasured > 0 { + o.insert("textUnmeasured".into(), json!(report.text_unmeasured)); + } + if report.frames_unmeasured > 0 { + o.insert("framesUnmeasured".into(), json!(report.frames_unmeasured)); + } } out } @@ -358,14 +383,16 @@ impl Ctx<'_> { fn walk(&mut self, root: NodeId) { let mut stack = vec![(root, String::new())]; while let Some((id, parent)) = stack.pop() { - if self.visited >= self.max_nodes { - self.truncated = true; - return; - } let Some(n) = self.doc.node(id) else { continue }; if !n.visible || n.locked || n.opacity <= 0.001 { continue; } + // Past the limit what follows is unchecked: say so once a further auditable node + // exists, not for a hidden or missing node the walk would skip anyway. + if self.visited >= self.max_nodes { + self.truncated = true; + return; + } self.visited += 1; let name = label(n); let path = if parent.is_empty() { name } else { format!("{parent} / {name}") }; @@ -431,7 +458,12 @@ impl Ctx<'_> { /// A fixed-size auto layout frame that clips children which overflow it: the rows exist but /// are invisible — the usual headless surprise. Hug frames grow, so they cannot clip. fn check_clipping(&mut self, n: &Node, path: &str) { - if self.measured_frames >= MAX_FRAMES_MEASURED || !n.clip || n.children.is_empty() || n.layout.is_none() { + if !n.clip || n.children.is_empty() || n.layout.is_none() { + return; + } + if self.measured_frames >= MAX_FRAMES_MEASURED { + // The frame was seen but not measured: an assertion on this rule cannot prove a pass. + self.frames_unmeasured += 1; return; } // An instance mirrors its main; the main is audited where it lives. @@ -769,11 +801,12 @@ impl Ctx<'_> { // A fixed-width text box whose stored height is shorter than the laid-out text clips or // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. - if !chars.is_empty() - && n.width > 0.0 - && self.measured < MAX_TEXT_MEASURED - && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) - { + if !chars.is_empty() && n.width > 0.0 && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) { + if self.measured >= MAX_TEXT_MEASURED { + // The box was seen but not laid out: an assertion on this rule cannot prove a pass. + self.text_unmeasured += 1; + return; + } self.measured += 1; let needed = figcraft_text::layout_cached(t, Some(n.width), None).height; if needed.is_finite() && needed > n.height + 1.0 { diff --git a/crates/engine/src/design/fix.rs b/crates/engine/src/design/fix.rs index 891e23bd4..7e890cdb6 100644 --- a/crates/engine/src/design/fix.rs +++ b/crates/engine/src/design/fix.rs @@ -29,6 +29,20 @@ pub(crate) fn run( ) -> Value { let settings = Settings::new(doc, preset); let before = collect(doc, roots, anchor, anchor_path, scope, &settings, max_nodes); + // A truncated walk would repair only the visited prefix and stay silent about the rest: the + // caller would leave with a "fixed" file that never was whole. Say so instead of guessing. + if before.truncated { + return json!({ + "scope": scope, + "dryRun": dry_run, + "changed": 0, + "skipped": 0, + "truncated": true, + "byRule": {}, + "before": tally(&before, &settings), + "after": tally(&before, &settings), + }); + } let targets: Vec<(NodeId, &'static str)> = before .findings .iter() @@ -62,6 +76,7 @@ pub(crate) fn run( "dryRun": dry_run, "changed": changed, "skipped": skipped, + "truncated": false, "byRule": by_rule, "before": tally(&before, &settings), "after": tally(&after, &settings), diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 03a8bfe59..6ce809c5f 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -135,7 +135,21 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { if report["truncated"].as_bool() == Some(true) { let nodes = report["nodes"].as_u64().unwrap_or(0); return Err(EngineError::Other(format!( - "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids), filter the rules, or raise `limit`, then assert again" + "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again" + ))); + } + // The overflow and clipping checks cap how much they measure per run, independently of + // `limit`: boxes or frames past the cap were seen but not measured, so a gate that includes + // those rules cannot prove a pass on a scope that big. + let unchecked: Vec = [("textUnmeasured", "layout.text-overflow"), ("framesUnmeasured", "layout.clipped")] + .into_iter() + .filter(|(key, rule)| report[*key].as_u64().unwrap_or(0) > 0 && filter.as_ref().is_none_or(|set| set.contains(*rule))) + .map(|(_, rule)| rule.to_string()) + .collect(); + if !unchecked.is_empty() { + return Err(EngineError::Other(format!( + "design review failed: the audit did not measure all of {} on this scope (past the per-run measure cap), so what it skipped is unchecked; audit a smaller scope, then assert again", + unchecked.join(", ") ))); } if !failing.is_empty() || score < min_score { @@ -314,7 +328,15 @@ fn ids_arg(cmd: &str, p: &Value) -> Result>> { fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, Option, String)> { let doc = s.doc()?; // `ids` names the layers directly (the review window fixes only the findings the user kept). + // An empty or unknown id checks nothing, which a CI gate must not mistake for a pass. if let Some(ids) = ids_arg(cmd, p)? { + if ids.is_empty() { + return Err(bad(cmd, "`ids` is empty: name at least one layer to audit, or drop `ids` for the selection, page or document")); + } + let missing: Vec = ids.iter().filter(|id| doc.node(**id).is_none()).map(|id| id.to_string()).collect(); + if !missing.is_empty() { + return Err(bad(cmd, format!("`ids` names layers that do not exist: {}", missing.join(", ")))); + } let roots = top_most(doc, &ids); let anchor = roots.first().copied(); let path = anchor.map(|id| node_label(doc, id)).unwrap_or_default(); diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 61145f215..099eba7e7 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -793,6 +793,94 @@ fn a_bad_limit_is_an_error() { assert_eq!(r["limit"], 1_000, "{r}"); } +#[test] +fn assert_refuses_a_scope_that_checks_nothing() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))); + // An empty id list and a missing id check nothing: a CI gate must not read that as a pass. + for ids in [json!([]), json!([999_999])] { + for cmd in ["design.audit", "design.assert", "design.fix"] { + let err = s.execute(cmd, &json!({"ids": ids})).unwrap_err().to_string(); + assert!(err.contains("`ids`"), "{cmd}: {err}"); + } + } + // The real layer still audits and gates as before. + let r = ex(&mut s, "design.audit", json!({"ids": [f]})); + assert_eq!(r["nodes"], 1, "{r}"); + assert!(s.execute("design.assert", &json!({"ids": [f]})).is_ok()); +} + +#[test] +fn a_limit_reached_by_hidden_nodes_is_not_truncation() { + let mut s = Session::new(); + let page = s.page().unwrap(); + { + let doc = s.doc_mut().unwrap(); + for i in 0..10 { + let id = doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + doc.get_mut(id).unwrap().visible = false; + } + } + let badge = id(&ex(&mut s, "text.create", json!({"text": "0", "x": 0.0, "y": 0.0, "props": {"fill": "#FFFFFF"}}))); + // Exactly limit visible nodes were audited; the stacked hidden ones are skips, not unchecked + // work, so the walk is whole and the badge's finding stands on its own. + let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 1_001, "rules": ["color.contrast"]})); + assert_eq!(r["truncated"], false, "{r}"); + assert!(has(&r, "color.contrast"), "{r}"); +} + +#[test] +fn fix_refuses_to_repair_a_truncated_scope() { + let mut s = Session::new(); + let page = s.page().unwrap(); + let off_grid = id(&ex( + &mut s, + "node.create", + json!({"type": "frame", "name": "Off grid", "x": 0.0, "y": 0.0, "width": 100.0, "height": 40.0, + "props": {"layout": "vertical", "gap": 13}}), + )); + { + let doc = s.doc_mut().unwrap(); + for i in 0..1_002 { + doc.create(page, NodeKind::Rectangle, &format!("Filler {i}"), 0.0, 0.0, 1.0, 1.0).unwrap(); + } + } + // The off-grid frame sorts behind the fillers, so the capped walk never reaches it: the fix + // must say the scope was incomplete rather than repair a prefix and claim success. + let r = ex(&mut s, "design.fix", json!({"scope": "page", "limit": 1_000, "rules": ["spacing.off-grid"]})); + assert_eq!(r["truncated"], true, "{r}"); + assert_eq!(r["changed"], 0, "{r}"); + let gap = s.doc().unwrap().node(off_grid).unwrap().layout.as_ref().unwrap().gap; + assert_eq!(gap, 13.0, "nothing was repaired under truncation"); + // With the walk whole the same request repairs. + let r = ex(&mut s, "design.fix", json!({"scope": "page", "limit": 2_000, "rules": ["spacing.off-grid"]})); + assert_eq!(r["truncated"], false, "{r}"); + assert_eq!(r["changed"], 1, "{r}"); +} + +#[test] +fn assert_refuses_a_scope_whose_measured_checks_were_capped() { + let mut s = Session::new(); + // 2,001 fixed-width overflowing boxes: the overflow check measures the first 2,000, so a + // gate on that rule cannot prove a pass over this scope. + for i in 0..2_001 { + ex( + &mut s, + "text.create", + json!({"text": "Overflowing line of interface copy", "name": &format!("Box {i}"), "x": 0.0, "y": 0.0, + "width": 60, "props": {"textAutoResize": "none"}}), + ); + } + let only = json!(["layout.text-overflow"]); + let audit = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); + assert!(audit["textUnmeasured"].as_u64().unwrap_or(0) >= 1, "{audit}"); + let err = s.execute("design.assert", &json!({"scope": "page", "rules": &only})).unwrap_err().to_string(); + assert!(err.contains("did not measure all of layout.text-overflow"), "{err}"); + // A gate that does not ask for the capped rule is unaffected. + let other = json!(["color.gradient"]); + assert!(s.execute("design.assert", &json!({"scope": "page", "rules": &other})).is_ok()); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); From 79fec6d855d9abccd46aa491ce39058a8a26c6d6 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 11:03:33 +0800 Subject: [PATCH 06/57] M13: drop an unused variable from the hidden-nodes test --- crates/engine/src/design/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 099eba7e7..f6dd06600 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -821,7 +821,7 @@ fn a_limit_reached_by_hidden_nodes_is_not_truncation() { doc.get_mut(id).unwrap().visible = false; } } - let badge = id(&ex(&mut s, "text.create", json!({"text": "0", "x": 0.0, "y": 0.0, "props": {"fill": "#FFFFFF"}}))); + ex(&mut s, "text.create", json!({"text": "0", "x": 0.0, "y": 0.0, "props": {"fill": "#FFFFFF"}})); // Exactly limit visible nodes were audited; the stacked hidden ones are skips, not unchecked // work, so the walk is whole and the badge's finding stands on its own. let r = ex(&mut s, "design.audit", json!({"scope": "page", "limit": 1_001, "rules": ["color.contrast"]})); From 26b7683d51c0500b61b279e469ea79cbbd8edcd9 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:53:07 +0800 Subject: [PATCH 07/57] M13: fix the review-integrity follow-ups --- crates/collab/src/change.rs | 9 +++++++++ crates/collab/src/diff_tests.rs | 18 ++++++++++++++++++ crates/collab/src/docprops.rs | 15 +++++++++++++++ crates/collab/src/replica.rs | 2 +- crates/engine/src/design/audit.rs | 20 ++++++++++++++------ crates/engine/src/design/mod.rs | 5 +++++ crates/engine/src/design/tests.rs | 28 ++++++++++++++++++++++++++++ 7 files changed, 90 insertions(+), 7 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index e7ecf85f4..4258565d0 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -326,6 +326,15 @@ impl Change { matches!(self, Change::Put { entry: Entry::Image(_), .. } | Change::Remove { entry: Entry::Image(_) }) } + /// Whether this edit carries review settings past the limits `design.configure` keeps: a + /// snapshot saved by a looser build may hold one, and opens without it (see + /// [`crate::docprops`], which refuses such a change inside an ordinary batch). + pub(crate) fn is_oversized_design_review(&self) -> bool { + let Change::SetDoc { prop: DocProp::DesignReview, value } = self else { return false }; + let Ok(config) = value.read::("design review") else { return false }; + config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS + } + /// Whether this only changes comment threads (a thread, their order, or all of them): what a /// comment link may send. pub fn is_comment(&self) -> bool { diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 9c252c3e9..33c96c4f8 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -60,6 +60,24 @@ fn design_review_settings_round_trip_and_reach_a_snapshot() { assert!(snapshot.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "a snapshot carries the review settings"); } +#[test] +fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_applies() { + let (a, _, _, _) = setup(); + // An edit peer trying to hand the file tens of thousands of radii is refused at apply. + let mut b = a.document().clone(); + b.design_review.radii = (0..40).map(|i| i as f64).collect(); + let mut r = a.clone(); + let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; + let err = r.apply(&[change.clone()], Mode::Strict).unwrap_err().to_string(); + assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); + // A snapshot holding settings over the limits (an old file's) still opens: like an image + // entry that fails today's checks, the oversized entry is left out of what it loads. + let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert_eq!(left_out, 1, "the oversized settings entry is the one left out"); + assert!(r2.document().design_review.radii.is_empty(), "the file opens without them"); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index 9a1305c62..f66b0688c 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -409,6 +409,21 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Index) -> Result { match change { Change::SetDoc { prop, value } => { + // A peer's review settings stay inside the limits `design.configure` enforces, so an + // edit cannot smuggle in tens of thousands of radii or accents for every corner + // check to scan. An oversized value arrives only in an old snapshot: snapshots keep + // applying as they are. + if *prop == DocProp::DesignReview { + let config: figcraft_doc::DesignReview = value.read("design review")?; + if config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS { + return Err(Error::Invalid(format!( + "design review: {} radii and {} brand colours pass the {} limit `design.configure` keeps", + config.radii.len(), + config.brand.len(), + figcraft_doc::MAX_RADII + ))); + } + } if set_scalar(doc, *prop, value)? { return Ok(*prop == DocProp::Libraries); } diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 547f0f59b..7e427970b 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -80,7 +80,7 @@ impl Replica { pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); - let left_out = r.apply_kept(&mut changes, Change::is_image)?; + let left_out = r.apply_kept(&mut changes, |c| Change::is_image(c) || Change::is_oversized_design_review(c))?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index ff7e1fbae..25a770c12 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -461,20 +461,23 @@ impl Ctx<'_> { if !n.clip || n.children.is_empty() || n.layout.is_none() { return; } - if self.measured_frames >= MAX_FRAMES_MEASURED { - // The frame was seen but not measured: an assertion on this rule cannot prove a pass. - self.frames_unmeasured += 1; - return; - } // An instance mirrors its main; the main is audited where it lives. if matches!(n.kind, NodeKind::Instance { .. }) { return; } let fixed_h = n.child_layout.sizing_h != Sizing::Hug; let fixed_v = n.child_layout.sizing_v != Sizing::Hug; + // A hug frame cannot clip, and the walk never measures it: not work the cap left behind. if !(fixed_h || fixed_v) { return; } + if self.measured_frames >= MAX_FRAMES_MEASURED { + // The frame was seen but not measured: an assertion on this rule cannot prove a pass. + if self.settings.enabled("layout.clipped") { + self.frames_unmeasured += 1; + } + return; + } let Some(frame) = self.doc.world_bounds(n.id) else { return }; let mut u: Option<(f64, f64, f64, f64)> = None; for child in &n.children { @@ -801,10 +804,15 @@ impl Ctx<'_> { // A fixed-width text box whose stored height is shorter than the laid-out text clips or // overlaps what follows it. Truncating boxes and auto-width boxes are intentional. + let overflow_asked = self.settings.enabled("layout.text-overflow"); if !chars.is_empty() && n.width > 0.0 && matches!(t.auto_resize, TextAutoResize::None | TextAutoResize::Height) { if self.measured >= MAX_TEXT_MEASURED { // The box was seen but not laid out: an assertion on this rule cannot prove a pass. - self.text_unmeasured += 1; + // A file that disabled the rule would never have measured it either way, so it + // does not make the run incomplete. + if overflow_asked { + self.text_unmeasured += 1; + } return; } self.measured += 1; diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 6ce809c5f..287ecb2d1 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -345,6 +345,11 @@ fn scope_of(s: &Session, cmd: &str, p: &Value) -> Result<(String, Vec, O let scope = scope_arg(cmd, p)?; let selection = s.selection(); let page = s.page()?; + // An explicitly empty selection checks nothing either; only the implicit default falls back + // to the page. A CI gate must not read an unchecked scope as a pass. + if scope.as_deref() == Some("selection") && selection.is_empty() { + return Err(bad(cmd, "nothing is selected: name `ids`, pick a scope of page or document, or select the layers to audit")); + } let (roots, label, anchor, path) = match scope.as_deref() { None if selection.is_empty() => (vec![page], "page", Some(page), node_label(doc, page)), None => selection_scope(doc, &selection), diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index f6dd06600..e537b4b13 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -879,6 +879,34 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { // A gate that does not ask for the capped rule is unaffected. let other = json!(["color.gradient"]); assert!(s.execute("design.assert", &json!({"scope": "page", "rules": &other})).is_ok()); + // A file that disabled the capped rule would not have measured it either way: the run is + // whole under its own settings, not incomplete. + ex(&mut s, "design.configure", json!({"disabled": ["layout.text-overflow"]})); + let audit = ex(&mut s, "design.audit", json!({"scope": "page"})); + assert!(audit["textUnmeasured"].is_null(), "{audit}"); + assert!(s.execute("design.assert", &json!({"scope": "page"})).is_ok(), "a disabled rule leaves nothing unchecked"); +} + +#[test] +fn assert_refuses_an_explicit_empty_selection() { + let mut s = Session::new(); + let f = id(&ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10}))); + s.set_selection(vec![]); + // With nothing selected, an explicit `selection` scope checks nothing: refused, while the + // implicit default (no scope) still falls back to the page and an explicit empty `ids` + // stays refused too. + for p in [json!({"scope": "selection"}), json!({"scope": "selection", "ids": []}), json!({"ids": []})] { + let err = s.execute("design.assert", &p).unwrap_err().to_string(); + assert!(err.contains("nothing is selected") || err.contains("`ids`"), "{p}: {err}"); + } + // The layer is there: selecting it audits and gates as usual. + s.set_selection(vec![f]); + let r = ex(&mut s, "design.audit", json!({"scope": "selection"})); + assert_eq!(r["nodes"], 1, "{r}"); + assert!(s.execute("design.assert", &json!({"scope": "selection"})).is_ok()); + // The implicit page default still works with nothing selected. + s.set_selection(vec![]); + assert!(s.execute("design.audit", &json!({})).is_ok()); } #[test] From edb6a84e9d65c2d5482c856739d863fb682bfb81 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:04:03 +0800 Subject: [PATCH 08/57] M13: borrow the change instead of cloning it in the limits test --- crates/collab/src/diff_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 33c96c4f8..874403685 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -68,7 +68,7 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_applies() { b.design_review.radii = (0..40).map(|i| i as f64).collect(); let mut r = a.clone(); let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; - let err = r.apply(&[change.clone()], Mode::Strict).unwrap_err().to_string(); + let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); // A snapshot holding settings over the limits (an old file's) still opens: like an image // entry that fails today's checks, the oversized entry is left out of what it loads. From e89a3041df0dd916ae5660f787f5b8bcb46e068d Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 09:01:46 +0800 Subject: [PATCH 09/57] M13: gate the review settings by client_version, clamp them in snapshots --- crates/collab/src/change.rs | 22 +++++---- crates/collab/src/diff_tests.rs | 19 ++++++-- crates/collab/src/docprops.rs | 21 +++++++++ crates/collab/src/message.rs | 13 +++++- crates/collab/src/replica.rs | 5 +- crates/collab/src/server.rs | 70 ++++++++++++++++++++++++++- crates/collab/src/server_tests.rs | 78 ++++++++++++++++++++++++++++++- docs/collab-protocol.md | 5 +- 8 files changed, 212 insertions(+), 21 deletions(-) diff --git a/crates/collab/src/change.rs b/crates/collab/src/change.rs index 4258565d0..44767ba8b 100644 --- a/crates/collab/src/change.rs +++ b/crates/collab/src/change.rs @@ -326,15 +326,6 @@ impl Change { matches!(self, Change::Put { entry: Entry::Image(_), .. } | Change::Remove { entry: Entry::Image(_) }) } - /// Whether this edit carries review settings past the limits `design.configure` keeps: a - /// snapshot saved by a looser build may hold one, and opens without it (see - /// [`crate::docprops`], which refuses such a change inside an ordinary batch). - pub(crate) fn is_oversized_design_review(&self) -> bool { - let Change::SetDoc { prop: DocProp::DesignReview, value } = self else { return false }; - let Ok(config) = value.read::("design review") else { return false }; - config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS - } - /// Whether this only changes comment threads (a thread, their order, or all of them): what a /// comment link may send. pub fn is_comment(&self) -> bool { @@ -344,6 +335,19 @@ impl Change { Change::Create { .. } | Change::Set { .. } | Change::Delete { .. } => false, } } + + /// Whether this writes the file's design review settings: a batch carrying one can't be read + /// by a peer that doesn't announce [`crate::message::DESIGN_REVIEW`], so the server keeps it + /// out of what it sends them ([`Self::without_design_review`]). + pub(crate) fn is_design_review(&self) -> bool { + matches!(self, Change::SetDoc { prop: DocProp::DesignReview, .. }) + } + + /// `changes` without the review-setting edits: what an older peer reads of a batch (its other + /// edits, order kept), or of a catch-up delta or snapshot. + pub(crate) fn without_design_review(changes: Vec) -> Vec { + changes.into_iter().filter(|c| !c.is_design_review()).collect() + } } impl Entry { diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 874403685..31b445486 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -61,21 +61,30 @@ fn design_review_settings_round_trip_and_reach_a_snapshot() { } #[test] -fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_applies() { +fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { let (a, _, _, _) = setup(); // An edit peer trying to hand the file tens of thousands of radii is refused at apply. let mut b = a.document().clone(); + b.design_review.preset = DesignPreset::Strict; + b.design_review.grid = 8.0; b.design_review.radii = (0..40).map(|i| i as f64).collect(); + b.design_review.brand = vec![Color::from_rgb8_const(1, 2, 3); 40]; + b.design_review.disabled = vec!["radius.off-scale".into()]; let mut r = a.clone(); let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); assert!(err.contains("pass the 32 limit `design.configure` keeps"), "{err}"); - // A snapshot holding settings over the limits (an old file's) still opens: like an image - // entry that fails today's checks, the oversized entry is left out of what it loads. + // A snapshot holding settings over the limits (an old file's) opens clamped to what fits: + // the preset, grid and disabled rules exactly as saved, the lists to the limit. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); - assert_eq!(left_out, 1, "the oversized settings entry is the one left out"); - assert!(r2.document().design_review.radii.is_empty(), "the file opens without them"); + assert_eq!(left_out, 0, "nothing needed leaving out"); + let cfg = &r2.document().design_review; + assert_eq!(cfg.preset, DesignPreset::Strict, "the preset survives"); + assert_eq!(cfg.grid, 8.0, "the grid survives"); + assert_eq!(cfg.disabled, vec!["radius.off-scale".to_string()], "the disabled rules survive"); + assert_eq!(cfg.radii, (0..32).map(|i| i as f64).collect::>(), "the radii keep their first 32"); + assert_eq!(cfg.brand, vec![Color::from_rgb8_const(1, 2, 3); 32], "the brand colours keep their first 32"); } #[test] diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index f66b0688c..a0c0b6c7a 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -403,6 +403,27 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } +/// Clamp the review settings a snapshot carries to the limits this build keeps, in place: an +/// older or looser snapshot may hold longer radii or brand lists, and the file opens with what +/// fits — the preset, grid and disabled rules exactly as saved. An ordinary edit is refused +/// instead (`apply_indexed`), and a peer that can't read the settings at all gets them left out +/// of what the server sends (`Change::without_design_review`). +pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { + for c in changes { + if let Change::SetDoc { prop: DocProp::DesignReview, value } = c + && let Ok(config) = value.read::("design review") + && (config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS) + { + let mut clamped = config; + clamped.radii.truncate(figcraft_doc::MAX_RADII); + clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS); + if let Ok(v) = Json::of(&clamped) { + *value = v; + } + } + } +} + /// Apply a document-level change, with the keyed lists' positions kept in `index` between the /// changes of one batch. Returns whether it can change which pages are listed (the library store /// page is never listed). diff --git a/crates/collab/src/message.rs b/crates/collab/src/message.rs index 07adbb2af..2c7392fc2 100644 --- a/crates/collab/src/message.rs +++ b/crates/collab/src/message.rs @@ -34,9 +34,15 @@ pub const COMMENTS: &str = "comments"; /// read it). pub const PACKED: &str = "packed"; +/// The word a client puts in its [`Hello::client_version`] when it reads +/// [`DocProp::DesignReview`](crate::DocProp::DesignReview): a server keeps review-setting changes +/// out of the batches, catch-up deltas and snapshots it sends to clients that don't say so +/// (older ones couldn't decode the variant at all). +pub const DESIGN_REVIEW: &str = "design-review"; + /// The `client_version` this build announces: its version, then what it reads beyond the protocol. pub fn client_version() -> String { - format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED}", env!("CARGO_PKG_VERSION")) + format!("{} {SIGNALS} {HOSTING} {COMMENTS} {PACKED} {DESIGN_REVIEW}", env!("CARGO_PKG_VERSION")) } /// Whether `client_version` announces `word`. @@ -64,6 +70,11 @@ pub fn reads_packed(client_version: &str) -> bool { announces(client_version, PACKED) } +/// A [`Hello::client_version`] that announces [`DESIGN_REVIEW`]. +pub fn reads_design_review(client_version: &str) -> bool { + announces(client_version, DESIGN_REVIEW) +} + /// Join a file's session. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Hello { diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index 7e427970b..b7cfb2752 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -77,10 +77,13 @@ impl Replica { /// [`from_snapshot`](Self::from_snapshot), and how many image entries it left out: a /// snapshot saved before the image checks may hold one they refuse, and opens without it. + /// Review settings past the current limits are clamped to them, not dropped (see + /// [`docprops::clamp_snapshot_design_review`]). pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); - let left_out = r.apply_kept(&mut changes, |c| Change::is_image(c) || Change::is_oversized_design_review(c))?; + docprops::clamp_snapshot_design_review(&mut changes); + let left_out = r.apply_kept(&mut changes, Change::is_image)?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 0f11792b7..e106472ba 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -8,7 +8,8 @@ use serde::{Deserialize, Serialize}; use crate::change::{Change, Entry, Family, Prop, Target}; use crate::message::{ - Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_signals, + Accepted, Access, CatchUp, ClientMsg, Hello, PROTOCOL, Peer, Presence, Processed, Resume, ServerMsg, Signal, reads_comments, reads_design_review, + reads_signals, }; use crate::replica::{Mode, Replica, create_change}; use crate::{Error, Limits, docprops, same_secret}; @@ -86,6 +87,10 @@ pub struct Server { journal: Option>, /// The connected clients that read signals (cursor chat, spotlight). signals: BTreeSet, + /// The connected clients that read the design review settings (`DocProp::DesignReview`): a + /// peer that doesn't announce them can't decode the variant, so the server keeps review + /// edits out of everything it sends them. + design_review: BTreeSet, /// Who spotlights now (a newcomer is told). spotlight: Option, /// Saved history this server restored or replayed left image entries out (or may give a @@ -146,6 +151,7 @@ impl Server { limited: BTreeMap::new(), journal: None, signals: BTreeSet::new(), + design_review: BTreeSet::new(), spotlight: None, resync: false, } @@ -333,12 +339,16 @@ impl Server { } // The log holds every batch after `floor`. let floor = self.log.front().map_or(self.seq, |a| a.seq.saturating_sub(1)); + let reads_design_review = reads_design_review(&hello.client_version); let catch_up = match resume { Some(r) if !self.resync && r.seq <= self.seq && r.seq >= floor => { CatchUp::Delta(self.log.iter().filter(|a| a.seq > r.seq).cloned().collect()) } _ => CatchUp::Snapshot(self.state.snapshot().map_err(|e| refuse(&e.to_string()))?), }; + // A peer that doesn't read the review settings can't decode them: its catch-up carries + // everything else. + let catch_up = filter_catch_up(catch_up, reads_design_review); let (id, secret) = match resume { Some(r) => (r.client_id, *self.secrets.entry(r.client_id).or_insert(r.secret)), None => { @@ -374,9 +384,20 @@ impl Server { } else { self.signals.remove(&id); } + if reads_design_review { + self.design_review.insert(id); + } else { + self.design_review.remove(&id); + } Ok((id, outs)) } + /// Whether every connected peer reads the design review settings: then a batch goes out as + /// one message, the common case. + fn everyone_reads_design_review(&self) -> bool { + self.peers.keys().all(|id| self.design_review.contains(id)) + } + /// Whether `r` may take its client id back: it carries the secret that id was given with, or /// (after a restart, which forgets secrets) a secret for an id nobody is connected as. fn may_resume(&self, r: &Resume) -> bool { @@ -393,6 +414,7 @@ impl Server { self.acked.remove(&id); self.limited.remove(&id); self.signals.remove(&id); + self.design_review.remove(&id); if self.spotlight == Some(id) { self.spotlight = None; } @@ -430,7 +452,7 @@ impl Server { let acc = Accepted { seq: self.seq, author: from, batch_id, changes }; self.remember(acc.clone()); self.note(Journal::Accepted(acc.clone())); - vec![Outgoing::All(ServerMsg::Changes(acc))] + self.relay_changes(acc) } Err(e) => { self.note(Journal::Refused { client: from, batch_id }); @@ -482,6 +504,30 @@ impl Server { } } + /// Send an accepted batch to every connected peer. A peer that doesn't read the review + /// settings can't decode them, so it gets the same batch (its seq, batch id and the peer's + /// own accounting included) with those edits left out and everything else in order. + fn relay_changes(&self, acc: Accepted) -> Vec { + if !acc.changes.iter().any(Change::is_design_review) || self.everyone_reads_design_review() { + return vec![Outgoing::All(ServerMsg::Changes(acc))]; + } + self.peers + .keys() + .copied() + .collect::>() + .into_iter() + .filter_map(|id| { + if self.design_review.contains(&id) { + Some(Outgoing::To(id, ServerMsg::Changes(acc.clone()))) + } else { + let mut filtered = acc.clone(); + filtered.changes = Change::without_design_review(filtered.changes); + (!filtered.changes.is_empty()).then_some(Outgoing::To(id, ServerMsg::Changes(filtered))) + } + }) + .collect() + } + /// Client `from` is called `name` from now on (cleaned): everyone, itself too, hears it as its /// `PeerJoined`, and newcomers' welcomes list it so. fn rename(&mut self, from: u32, name: String) -> Vec { @@ -704,3 +750,23 @@ pub fn weight(changes: &[Change]) -> usize { }) .fold(0, usize::saturating_add) } + +/// A catch-up a peer that doesn't read the design review settings can decode: the review-setting +/// edits are left out of a delta and out of a snapshot, everything else as it was. +fn filter_catch_up(cu: CatchUp, reads_design_review: bool) -> CatchUp { + if reads_design_review { + return cu; + } + match cu { + CatchUp::Delta(list) => CatchUp::Delta( + list.into_iter() + .map(|mut a| { + a.changes = Change::without_design_review(a.changes); + a + }) + .collect(), + ), + CatchUp::Snapshot(changes) => CatchUp::Snapshot(Change::without_design_review(changes)), + packed => packed, + } +} diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index aafff946d..f46127169 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -2,8 +2,8 @@ use figcraft_doc::{Document, Node, NodeId, NodeKind}; -use crate::change::{Change, Entry, Json, Prop}; -use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg}; +use crate::change::{Change, DocProp, Entry, Json, Prop}; +use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; use crate::replica::Mode; use crate::{Client, Limits, NoRecompute, Outgoing, Server}; @@ -39,6 +39,22 @@ fn for_client(out: &[Outgoing], to: u32) -> Vec { .collect() } +/// A hello whose `client_version` says exactly `version` (what an older or newer build announces). +fn hello_of(version: &str) -> Hello { + Hello { client_version: version.to_string(), ..hello("tok") } +} + +/// The changes an `Accepted` relay or catch-up carries, or none. +fn accepted_changes(msgs: &[ServerMsg]) -> Vec<&Change> { + msgs.iter() + .filter_map(|m| match m { + ServerMsg::Changes(a) => Some(a.changes.iter().collect::>()), + _ => None, + }) + .flatten() + .collect() +} + fn edit(c: &mut Client, f: impl FnOnce(&mut Document)) -> ClientMsg { let mut d = c.document().clone(); f(&mut d); @@ -364,3 +380,61 @@ fn junk_batches_never_panic_and_never_corrupt_the_document() { assert!(s.document().validate().is_empty(), "{:?}", s.document().validate()); } } + +#[test] +fn the_client_version_announces_the_design_review() { + assert!(reads_design_review(&client_version())); + assert!(!reads_design_review("0.18.0 signals hosting comments packed")); +} + +/// A capable editor, a peer built before the review existed, and a mixed batch: the old peer +/// hears the same batch without the review-setting edit, the new peer hears it whole. +#[test] +fn a_review_edit_reaches_only_the_peers_that_read_it() { + let (d, _, _) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // One batch: rename the document (everyone) and set the review grid (capable peers only). + let batch = vec![ + Change::SetDoc { prop: DocProp::Name, value: Json::of("Renamed").unwrap() }, + Change::SetDoc { prop: DocProp::DesignReview, value: Json(serde_json::json!({"preset": "strict", "grid": 8.0})) }, + ]; + let out = s.receive(capable.id(), ClientMsg::Changes { base_seq: s.seq(), batch_id: 1, changes: batch }); + let for_old = for_client(&out, old.id()); + assert!(accepted_changes(&for_old).iter().all(|c| !c.is_design_review()), "the old peer's copy carries no review edit: {:?}", for_old); + assert!( + accepted_changes(&for_old).iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), + "the old peer still hears the rename: {:?}", + for_old + ); + let for_new = for_client(&out, capable.id()); + assert_eq!(accepted_changes(&for_new).len(), 2, "the capable peer hears both: {for_new:?}"); + + // A capable newcomer's catch-up (a fresh join, so a snapshot) carries the settings. + let (_, out) = s.join(hello("tok")).unwrap(); + let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. }))) + else { + panic!("no welcome"); + }; + let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") }; + assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::DesignReview, .. })), "{changes:?}"); + + // An old newcomer's catch-up carries none, and still has the rename. + let (_, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let Some(Outgoing::To(_, ServerMsg::Welcome { catch_up, .. })) = + out.into_iter().find(|o| matches!(o, Outgoing::To(_, ServerMsg::Welcome { .. }))) + else { + panic!("no welcome"); + }; + let crate::message::CatchUp::Snapshot(changes) = catch_up else { panic!("not a snapshot") }; + assert!(changes.iter().all(|c| !c.is_design_review()), "{changes:?}"); + assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), "{changes:?}"); +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 1a7e77052..31c07420b 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -149,7 +149,10 @@ As built: still increasing keeps its keys) and re-spaces a parent whose keys would grow past 48 characters. - **Document-level objects covered now**: the file name, the current page, document colours, the colour profile, image presets, annotation categories, the design review settings - (`DocProp::DesignReview`) and library data (whole values); styles, + (`DocProp::DesignReview`, sent only to clients whose `client_version` announces + `design-review`; a client that doesn't gets every batch, catch-up delta and snapshot without + them, and a snapshot saved with longer lists opens clamped to the limits `design.configure` + keeps) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content hash, the encoded bytes as base64; as an entry applies the claim is checked: every key is From 846e69f206616964dd0d5b4bfa0fa5512c55b6bb Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:17:32 +0800 Subject: [PATCH 10/57] M13: keep an older peer in step through a review-only batch --- crates/collab/src/server.rs | 13 +++++---- crates/collab/src/server_tests.rs | 47 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 6 deletions(-) diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index e106472ba..58ad309bb 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -511,18 +511,19 @@ impl Server { if !acc.changes.iter().any(Change::is_design_review) || self.everyone_reads_design_review() { return vec![Outgoing::All(ServerMsg::Changes(acc))]; } + // Every peer hears the batch, even one with nothing left for it: the batch still carries + // the next sequence number, and a peer that skipped it would reject its next ordinary + // batch as out of order. self.peers .keys() .copied() - .collect::>() - .into_iter() - .filter_map(|id| { - if self.design_review.contains(&id) { - Some(Outgoing::To(id, ServerMsg::Changes(acc.clone()))) + .map(|id| { + if self.design_review.contains(&id) || id == acc.author { + Outgoing::To(id, ServerMsg::Changes(acc.clone())) } else { let mut filtered = acc.clone(); filtered.changes = Change::without_design_review(filtered.changes); - (!filtered.changes.is_empty()).then_some(Outgoing::To(id, ServerMsg::Changes(filtered))) + Outgoing::To(id, ServerMsg::Changes(filtered)) } }) .collect() diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index f46127169..e26728835 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -438,3 +438,50 @@ fn a_review_edit_reaches_only_the_peers_that_read_it() { assert!(changes.iter().all(|c| !c.is_design_review()), "{changes:?}"); assert!(changes.iter().any(|c| matches!(c, Change::SetDoc { prop: DocProp::Name, .. })), "{changes:?}"); } + +/// A review-only batch advances the server sequence for every peer. An older peer must still be +/// sent the accepted batch, empty as it is, or it falls a sequence behind and refuses what +/// follows. +#[test] +fn a_review_only_batch_keeps_an_older_peer_in_step() { + let (d, _, frame) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let mut capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let mut old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // Only the review settings change, so this batch has nothing for the older peer. + let msg = edit(&mut capable, |d| d.design_review.grid = 8.0); + let ClientMsg::Changes { changes, .. } = &msg else { panic!("not a batch") }; + assert!(!changes.is_empty() && changes.iter().all(Change::is_design_review), "review only: {changes:?}"); + let out = s.receive(capable.id(), msg); + assert_eq!(s.seq(), 1); + let to_old = for_client(&out, old.id()); + let empty = to_old.iter().any(|m| matches!(m, ServerMsg::Changes(a) if a.changes.is_empty())); + assert!(empty, "the older peer is told the batch happened: {to_old:?}"); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in to_old { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + + // The next ordinary edit still lands for it. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "After", 0.0, 0.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(1), "the new node is there"); +} From 38eec9895d3a72172eebdb8268a396bf2b474e28 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:56:47 +0800 Subject: [PATCH 11/57] M13: a review-only batch reaches a peer that was away as an empty delta --- crates/collab/src/server_tests.rs | 71 ++++++++++++++++++++++++++++++- docs/collab-protocol.md | 3 +- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/crates/collab/src/server_tests.rs b/crates/collab/src/server_tests.rs index e26728835..8979cb213 100644 --- a/crates/collab/src/server_tests.rs +++ b/crates/collab/src/server_tests.rs @@ -3,7 +3,7 @@ use figcraft_doc::{Document, Node, NodeId, NodeKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; -use crate::message::{ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; +use crate::message::{CatchUp, ClientMsg, Hello, PROTOCOL, Presence, ServerMsg, client_version, reads_design_review}; use crate::replica::Mode; use crate::{Client, Limits, NoRecompute, Outgoing, Server}; @@ -485,3 +485,72 @@ fn a_review_only_batch_keeps_an_older_peer_in_step() { assert_eq!(old.seq(), s.seq()); assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(1), "the new node is there"); } + +/// The same batch through the other catch-up path: a peer that was away comes back with a delta, +/// and the review-only batch is there as an accepted batch with nothing in it for it, so its +/// sequence carries on and the edits after it apply. +#[test] +fn a_review_only_batch_is_an_empty_delta_for_a_peer_that_was_away() { + let (d, _, frame) = doc(); + let mut s = Server::new(d, "tok", Limits::default()); + let mut capable = join(&mut s); + let (old_id, out) = s.join(hello_of("0.18.0 signals hosting comments packed")).unwrap(); + let mut old = { + let Some(Outgoing::To(_, welcome)) = out.into_iter().next() else { panic!("no welcome") }; + Client::join(welcome).unwrap() + }; + assert_eq!(old.id(), old_id); + + // One ordinary edit, so the peer's resume point sits before the review-only batch. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "Before", 0.0, 0.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), 1); + + // It drops; only the review settings change while it is away. + old.disconnect(); + let msg = edit(&mut capable, |d| d.design_review.grid = 8.0); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, capable.id()) { + capable.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(s.seq(), 2); + + // It comes back: the delta holds the batch, empty, and its sequence carries on. + let ClientMsg::Hello(h) = old.reconnect(hello_of("0.18.0 signals hosting comments packed")) else { + panic!("not a hello"); + }; + let (id, out) = s.join(h).unwrap(); + assert_eq!(id, old.id()); + let welcome = out + .into_iter() + .find_map(|o| match o { + Outgoing::To(to, w @ ServerMsg::Welcome { .. }) if to == id => Some(w), + _ => None, + }) + .unwrap_or_else(|| panic!("no welcome")); + assert!( + matches!(&welcome, ServerMsg::Welcome { catch_up: CatchUp::Delta(list), .. } if list.len() == 1 && list[0].changes.is_empty()), + "{welcome:?}" + ); + old.receive(welcome, &NoRecompute).unwrap(); + assert_eq!(old.seq(), s.seq()); + + // And the next ordinary edit still applies. + let msg = edit(&mut capable, |d| { + d.create(frame, NodeKind::Rectangle, "After", 0.0, 20.0, 10.0, 10.0).unwrap(); + }); + let out = s.receive(capable.id(), msg); + for m in for_client(&out, old.id()) { + old.receive(m, &NoRecompute).unwrap(); + } + assert_eq!(old.seq(), s.seq()); + assert_eq!(old.document().node(frame).map(|n| n.children.len()), Some(2), "both nodes are there"); +} diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 31c07420b..6cada9a59 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -151,7 +151,8 @@ As built: colour profile, image presets, annotation categories, the design review settings (`DocProp::DesignReview`, sent only to clients whose `client_version` announces `design-review`; a client that doesn't gets every batch, catch-up delta and snapshot without - them, and a snapshot saved with longer lists opens clamped to the limits `design.configure` + them, and an accepted batch still reaches it when nothing of it is left, so sequence numbers + never skip; a snapshot saved with longer lists opens clamped to the limits `design.configure` keeps) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content From 9d8c1efc06c82e588fb1f262b58b40366600bb68 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 10:56:48 +0800 Subject: [PATCH 12/57] M13: refuse a rule filter that names nothing --- crates/engine/src/design/mod.rs | 8 ++++++++ crates/engine/src/design/tests.rs | 12 ++++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 287ecb2d1..57fa03cb1 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -397,6 +397,14 @@ fn severity_arg(cmd: &str, p: &Value) -> Result { fn filter_arg(cmd: &str, p: &Value) -> Result>> { let Some(v) = params::get(p, "rules") else { return Ok(None) }; let Value::Array(items) = v else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; + // A filter that names nothing checks nothing: a gate would pass over a review that never + // ran, the same way a truncated audit would. + if items.is_empty() { + return Err(bad( + cmd, + "`rules` names no rule, so nothing would be checked; list at least one (design.rules has them) or leave `rules` out to check them all", + )); + } let mut set = BTreeSet::new(); for item in items { let Some(s) = item.as_str() else { return Err(bad(cmd, "`rules` must be an array of rule ids")) }; diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index e537b4b13..1dd2ec3ff 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -909,6 +909,18 @@ fn assert_refuses_an_explicit_empty_selection() { assert!(s.execute("design.audit", &json!({})).is_ok()); } +#[test] +fn an_empty_rule_filter_is_refused() { + let mut s = Session::new(); + ex(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + for cmd in ["design.audit", "design.assert", "design.fix"] { + let err = s.execute(cmd, &json!({"scope": "page", "rules": []})).unwrap_err().to_string(); + assert!(err.contains("`rules`"), "{cmd}: {err}"); + } + // Naming a rule still works. + assert!(ex(&mut s, "design.audit", json!({"scope": "page", "rules": ["color.accents"]})).is_object()); +} + #[test] fn hardcoded_values_that_match_variables_are_reported() { let mut s = Session::new(); From 5f2c81beb2b04818ac2fe6a78c364f63e03f0a1d Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:48:52 +0800 Subject: [PATCH 13/57] M13: the audit names the rules it could not check, and gates read them --- crates/engine/src/design/audit.rs | 18 +++++++++++++++++- crates/engine/src/design/mod.rs | 25 +++++++++++++++---------- crates/engine/src/design/tests.rs | 12 ++++++++++++ 3 files changed, 44 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 25a770c12..5045aee52 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -358,6 +358,21 @@ pub(crate) fn run( *by_rule.entry(f.rule).or_default() += 1; } let findings: Vec = shown.into_iter().map(Finding::json).collect(); + // What the walk could not check, by rule: past the node limit it looked at nothing more, and + // past a measure cap it saw layers without measuring them. A gate reads this list, so a new + // cap somewhere in the walk fails it without a second place to remember. + let mut unchecked: Vec = Vec::new(); + if report.truncated { + for r in super::rules::RULES.iter().filter(|r| settings.enabled(r.id)) { + unchecked.push(json!({"rule": r.id, "reason": "truncated"})); + } + } else { + for (rule, layers) in [("layout.text-overflow", report.text_unmeasured), ("layout.clipped", report.frames_unmeasured)] { + if layers > 0 && settings.enabled(rule) { + unchecked.push(json!({"rule": rule, "reason": "measure-cap", "layers": layers})); + } + } + } let mut out = settings.json(); if let Some(o) = out.as_object_mut() { o.insert("scope".into(), json!(scope)); @@ -368,7 +383,8 @@ pub(crate) fn run( o.insert("limit".into(), json!(report.limit)); o.insert("findings".into(), json!(findings)); o.insert("truncated".into(), json!(report.truncated)); - // Checks the walk capped before finishing: what they did not measure is unchecked. + o.insert("unchecked".into(), json!(unchecked)); + // How many layers each capped check left unmeasured, for the window and agents. if report.text_unmeasured > 0 { o.insert("textUnmeasured".into(), json!(report.text_unmeasured)); } diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index 57fa03cb1..f4d308cf5 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -30,7 +30,7 @@ pub fn specs() -> Vec { spec!( "design.audit", "Check design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated} reads the design and reports the AI-slop tells; changes nothing", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], minSeverity?: low|medium|high (default low), preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes; the contrast check uses them), limit?: 1000-1000000 (nodes before the report says truncated; default 50000)} → {preset, grid, modes?, scope, score, counts: {high, medium, low}, byRule: {rule: count}, nodes, limit, findings: [{rule, severity, node, path, message, fixable, suggestion?}], truncated, unchecked: [{rule, reason, layers?}]} reads the design and reports the AI-slop tells; changes nothing (unchecked names the rules the run could not check: truncated, or a measure cap)", false, audit_cmd ), @@ -44,7 +44,7 @@ pub fn specs() -> Vec { spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit was truncated at the node limit it ran with (what it did not reach is unchecked: narrow the scope, filter the rules or raise `limit`); read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit could not check a rule it asked for (truncated at the node limit it ran with, or past a measure cap: what it did not reach is unchecked, so narrow the scope, filter the rules or raise `limit`); read-only, for CI", false, assert_cmd ), @@ -138,14 +138,19 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again" ))); } - // The overflow and clipping checks cap how much they measure per run, independently of - // `limit`: boxes or frames past the cap were seen but not measured, so a gate that includes - // those rules cannot prove a pass on a scope that big. - let unchecked: Vec = [("textUnmeasured", "layout.text-overflow"), ("framesUnmeasured", "layout.clipped")] - .into_iter() - .filter(|(key, rule)| report[*key].as_u64().unwrap_or(0) > 0 && filter.as_ref().is_none_or(|set| set.contains(*rule))) - .map(|(_, rule)| rule.to_string()) - .collect(); + // What the audit reported as unchecked, restricted to the rules this gate asked for. The + // audit names each rule it could not check (`limit` truncation is handled above with its own + // advice), so a cap added there fails this gate without a list here to keep in step. + let unchecked: Vec<&str> = report["unchecked"] + .as_array() + .map(|v| { + v.iter() + .filter(|e| e["reason"].as_str() == Some("measure-cap")) + .filter_map(|e| e["rule"].as_str()) + .filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule))) + .collect() + }) + .unwrap_or_default(); if !unchecked.is_empty() { return Err(EngineError::Other(format!( "design review failed: the audit did not measure all of {} on this scope (past the per-run measure cap), so what it skipped is unchecked; audit a smaller scope, then assert again", diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index 1dd2ec3ff..b01242b4b 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -750,6 +750,12 @@ fn assert_fails_when_the_audit_is_truncated() { let r = ex(&mut s, "design.audit", json!({"scope": "page"})); assert_eq!(r["truncated"], true, "{r}"); assert_eq!(r["limit"], 50_000, "{r}"); + // Every rule the file enables is named as unchecked: the report says what it could not see, + // which is what the gate reads. + let unchecked = r["unchecked"].as_array().map(Vec::as_slice).unwrap_or_default(); + assert!(unchecked.len() >= 20, "{r}"); + assert!(unchecked.iter().all(|e| e["reason"] == "truncated"), "{r}"); + assert!(unchecked.iter().any(|e| e["rule"] == "color.contrast"), "{r}"); // The gate must not turn a truncated audit into a pass at score 100. let err = s.execute("design.assert", &json!({"scope": "page", "failOn": "high"})).unwrap_err().to_string(); assert!(err.contains("stopped at the 50000-node limit"), "{err}"); @@ -874,6 +880,11 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { let only = json!(["layout.text-overflow"]); let audit = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &only})); assert!(audit["textUnmeasured"].as_u64().unwrap_or(0) >= 1, "{audit}"); + // The report names the rule the cap left unmeasured, which is what the gate reads. + let unchecked = audit["unchecked"].as_array().map(Vec::as_slice).unwrap_or_default(); + assert_eq!(unchecked.len(), 1, "{audit}"); + assert_eq!(unchecked[0]["rule"], "layout.text-overflow", "{audit}"); + assert_eq!(unchecked[0]["reason"], "measure-cap", "{audit}"); let err = s.execute("design.assert", &json!({"scope": "page", "rules": &only})).unwrap_err().to_string(); assert!(err.contains("did not measure all of layout.text-overflow"), "{err}"); // A gate that does not ask for the capped rule is unaffected. @@ -884,6 +895,7 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { ex(&mut s, "design.configure", json!({"disabled": ["layout.text-overflow"]})); let audit = ex(&mut s, "design.audit", json!({"scope": "page"})); assert!(audit["textUnmeasured"].is_null(), "{audit}"); + assert!(audit["unchecked"].as_array().is_some_and(Vec::is_empty), "{audit}"); assert!(s.execute("design.assert", &json!({"scope": "page"})).is_ok(), "a disabled rule leaves nothing unchecked"); } From 15d0a4683c94f83bee36e9fa473b391533f64e74 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Fri, 13 Nov 2026 11:48:53 +0800 Subject: [PATCH 14/57] M13: cap the disabled-rule list at the wire like radii and brand --- crates/collab/src/diff_tests.rs | 20 ++++++++++++++++- crates/collab/src/docprops.rs | 38 ++++++++++++++++++++------------- crates/doc/src/design_review.rs | 4 ++++ crates/doc/src/lib.rs | 2 +- 4 files changed, 47 insertions(+), 17 deletions(-) diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 31b445486..4aafc891c 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use std::sync::Arc; use figcraft_color::{Color, Paint}; -use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, Message, Node, NodeId, NodeKind, Style, StyleKind}; +use figcraft_doc::{Comment, DesignPreset, DevSnapshot, Document, ImageData, MAX_DISABLED, Message, Node, NodeId, NodeKind, Style, StyleKind}; use crate::change::{Change, DocProp, Entry, Json, Prop}; use crate::replica::{Mode, Replica}; @@ -87,6 +87,24 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { assert_eq!(cfg.brand, vec![Color::from_rgb8_const(1, 2, 3); 32], "the brand colours keep their first 32"); } +#[test] +fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them() { + let (a, _, _, _) = setup(); + let mut b = a.document().clone(); + b.design_review.disabled = (0..200).map(|i| format!("rule.{i}")).collect(); + let mut r = a.clone(); + let change = Change::SetDoc { prop: DocProp::DesignReview, value: Json::of(&b.design_review).unwrap() }; + let err = r.apply(std::slice::from_ref(&change), Mode::Strict).unwrap_err().to_string(); + assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}"); + // A snapshot with a longer list opens with the ones that fit, not without the settings. + let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; + let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert_eq!(left_out, 0, "nothing needed leaving out"); + let cfg = &r2.document().design_review; + assert_eq!(cfg.disabled.len(), MAX_DISABLED, "the list keeps its first {MAX_DISABLED}"); + assert_eq!(cfg.disabled.first().map(String::as_str), Some("rule.0")); +} + #[test] fn creations_moves_reorders_and_deletions_round_trip() { let (a, page, frame, kids) = setup(); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index a0c0b6c7a..abdf8f3c8 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -403,20 +403,33 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } +/// The review-settings lists that hold more than this build keeps, as (what, how many, the cap). +fn review_lists_over_limit(c: &figcraft_doc::DesignReview) -> Vec<(&'static str, usize, usize)> { + [ + ("radii", c.radii.len(), figcraft_doc::MAX_RADII), + ("brand colours", c.brand.len(), figcraft_doc::MAX_BRAND_COLORS), + ("disabled rules", c.disabled.len(), figcraft_doc::MAX_DISABLED), + ] + .into_iter() + .filter(|(_, have, max)| have > max) + .collect() +} + /// Clamp the review settings a snapshot carries to the limits this build keeps, in place: an -/// older or looser snapshot may hold longer radii or brand lists, and the file opens with what -/// fits — the preset, grid and disabled rules exactly as saved. An ordinary edit is refused -/// instead (`apply_indexed`), and a peer that can't read the settings at all gets them left out -/// of what the server sends (`Change::without_design_review`). +/// older or looser snapshot may hold longer radii, brand or disabled lists, and the file opens +/// with what fits — the preset, grid and the rest of each list exactly as saved. An ordinary edit +/// is refused instead (`apply_indexed`), and a peer that can't read the settings at all gets them +/// left out of what the server sends (`Change::without_design_review`). pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { for c in changes { if let Change::SetDoc { prop: DocProp::DesignReview, value } = c && let Ok(config) = value.read::("design review") - && (config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS) + && !review_lists_over_limit(&config).is_empty() { let mut clamped = config; clamped.radii.truncate(figcraft_doc::MAX_RADII); clamped.brand.truncate(figcraft_doc::MAX_BRAND_COLORS); + clamped.disabled.truncate(figcraft_doc::MAX_DISABLED); if let Ok(v) = Json::of(&clamped) { *value = v; } @@ -431,18 +444,13 @@ pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Ind match change { Change::SetDoc { prop, value } => { // A peer's review settings stay inside the limits `design.configure` enforces, so an - // edit cannot smuggle in tens of thousands of radii or accents for every corner - // check to scan. An oversized value arrives only in an old snapshot: snapshots keep - // applying as they are. + // edit cannot smuggle in tens of thousands of radii, accents or rule ids for every + // check to scan. An oversized value arrives only in an old snapshot, and the snapshot + // path clamps it (`clamp_snapshot_design_review`). if *prop == DocProp::DesignReview { let config: figcraft_doc::DesignReview = value.read("design review")?; - if config.radii.len() > figcraft_doc::MAX_RADII || config.brand.len() > figcraft_doc::MAX_BRAND_COLORS { - return Err(Error::Invalid(format!( - "design review: {} radii and {} brand colours pass the {} limit `design.configure` keeps", - config.radii.len(), - config.brand.len(), - figcraft_doc::MAX_RADII - ))); + if let Some((what, have, max)) = review_lists_over_limit(&config).first() { + return Err(Error::Invalid(format!("design review: {have} {what} pass the {max} limit `design.configure` keeps"))); } } if set_scalar(doc, *prop, value)? { diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs index c2fce64c8..002fe6d53 100644 --- a/crates/doc/src/design_review.rs +++ b/crates/doc/src/design_review.rs @@ -50,6 +50,10 @@ pub const GRID_MAX: f64 = 64.0; pub const MAX_RADII: usize = 32; pub const MAX_BRAND_COLORS: usize = 32; +/// Most rules a file turns off. The rule catalog is smaller than this: the cap keeps a hand-edited +/// or older file from carrying thousands of ids every review would read. +pub const MAX_DISABLED: usize = 64; + /// A file's design review settings. The default is the recommended preset on a 4px grid with the /// 4px radius scale and no brand palette. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index c25d0e66e..957822479 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -33,7 +33,7 @@ pub use board_mindmap::{MIND_GAP_X, MIND_GAP_Y, MIND_MAX_DEPTH, MIND_MAX_NODES, pub use board_route::{END_GAP, MAX_RUNS, RouteEnd, attach_points, attached_sides, path_handles, reshaped, route_along, route_points}; pub use colors::*; pub use comments::*; -pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_RADII}; +pub use design_review::{DesignPreset, DesignReview, GRID_MAX, GRID_MIN, MAX_BRAND_COLORS, MAX_DISABLED, MAX_RADII}; pub use facilitation::*; pub use figcraft_color as color; pub use figcraft_geom as geom; From 1205a4cc307ceffd091a43be702e2f2fd9117552 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:26:29 +0800 Subject: [PATCH 15/57] M13: a session whose snapshot was clamped catches resuming clients up with it --- crates/collab/src/diff_tests.rs | 6 +- crates/collab/src/docprops.rs | 32 ++++------- crates/collab/src/reconnect_tests.rs | 85 ++++++++++++++++++++++++++++ crates/collab/src/replica.rs | 12 ++-- crates/collab/src/server.rs | 8 ++- 5 files changed, 113 insertions(+), 30 deletions(-) diff --git a/crates/collab/src/diff_tests.rs b/crates/collab/src/diff_tests.rs index 4aafc891c..32edaba7c 100644 --- a/crates/collab/src/diff_tests.rs +++ b/crates/collab/src/diff_tests.rs @@ -77,7 +77,8 @@ fn an_edit_past_the_review_limits_is_refused_but_a_snapshot_clamps() { // A snapshot holding settings over the limits (an old file's) opens clamped to what fits: // the preset, grid and disabled rules exactly as saved, the lists to the limit. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; - let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert!(clamped, "the settings needed clamping, and the caller is told"); assert_eq!(left_out, 0, "nothing needed leaving out"); let cfg = &r2.document().design_review; assert_eq!(cfg.preset, DesignPreset::Strict, "the preset survives"); @@ -98,7 +99,8 @@ fn an_edit_with_too_many_disabled_rules_is_refused_and_a_snapshot_truncates_them assert!(err.contains("200 disabled rules pass the 64 limit `design.configure` keeps"), "{err}"); // A snapshot with a longer list opens with the ones that fit, not without the settings. let snap = diff(&Replica::new(Document::without_pages("")), &b).unwrap().changes; - let (r2, left_out) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + let (r2, left_out, clamped) = Replica::from_snapshot_leaving_out(&snap).unwrap(); + assert!(clamped); assert_eq!(left_out, 0, "nothing needed leaving out"); let cfg = &r2.document().design_review; assert_eq!(cfg.disabled.len(), MAX_DISABLED, "the list keeps its first {MAX_DISABLED}"); diff --git a/crates/collab/src/docprops.rs b/crates/collab/src/docprops.rs index abdf8f3c8..ae7299511 100644 --- a/crates/collab/src/docprops.rs +++ b/crates/collab/src/docprops.rs @@ -403,28 +403,18 @@ pub(crate) fn apply(doc: &mut Document, change: &Change) -> Result apply_indexed(doc, change, &mut Index::default()) } -/// The review-settings lists that hold more than this build keeps, as (what, how many, the cap). -fn review_lists_over_limit(c: &figcraft_doc::DesignReview) -> Vec<(&'static str, usize, usize)> { - [ - ("radii", c.radii.len(), figcraft_doc::MAX_RADII), - ("brand colours", c.brand.len(), figcraft_doc::MAX_BRAND_COLORS), - ("disabled rules", c.disabled.len(), figcraft_doc::MAX_DISABLED), - ] - .into_iter() - .filter(|(_, have, max)| have > max) - .collect() -} - -/// Clamp the review settings a snapshot carries to the limits this build keeps, in place: an -/// older or looser snapshot may hold longer radii, brand or disabled lists, and the file opens -/// with what fits — the preset, grid and the rest of each list exactly as saved. An ordinary edit -/// is refused instead (`apply_indexed`), and a peer that can't read the settings at all gets them -/// left out of what the server sends (`Change::without_design_review`). -pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { +/// Clamp the review settings a snapshot carries to the limits this build keeps, in place, and say +/// whether it changed them: an older or looser snapshot may hold longer radii, brand or disabled +/// lists, and the file opens with what fits — the preset, grid and the rest of each list exactly +/// as saved. An ordinary edit is refused instead (`apply_indexed`), and a peer that can't read the +/// settings at all gets them left out of what the server sends +/// (`Change::without_design_review`). +pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) -> bool { + let mut clamped_any = false; for c in changes { if let Change::SetDoc { prop: DocProp::DesignReview, value } = c && let Ok(config) = value.read::("design review") - && !review_lists_over_limit(&config).is_empty() + && !config.over_limits().is_empty() { let mut clamped = config; clamped.radii.truncate(figcraft_doc::MAX_RADII); @@ -432,9 +422,11 @@ pub(crate) fn clamp_snapshot_design_review(changes: &mut Vec) { clamped.disabled.truncate(figcraft_doc::MAX_DISABLED); if let Ok(v) = Json::of(&clamped) { *value = v; + clamped_any = true; } } } + clamped_any } /// Apply a document-level change, with the keyed lists' positions kept in `index` between the @@ -449,7 +441,7 @@ pub(crate) fn apply_indexed(doc: &mut Document, change: &Change, index: &mut Ind // path clamps it (`clamp_snapshot_design_review`). if *prop == DocProp::DesignReview { let config: figcraft_doc::DesignReview = value.read("design review")?; - if let Some((what, have, max)) = review_lists_over_limit(&config).first() { + if let Some((what, have, max)) = config.over_limits().first() { return Err(Error::Invalid(format!("design review: {have} {what} pass the {max} limit `design.configure` keeps"))); } } diff --git a/crates/collab/src/reconnect_tests.rs b/crates/collab/src/reconnect_tests.rs index a5998feea..af13b5042 100644 --- a/crates/collab/src/reconnect_tests.rs +++ b/crates/collab/src/reconnect_tests.rs @@ -291,6 +291,91 @@ fn random_drops_and_reconnects_converge() { assert!(snapshots > 0, "no reconnect needed a snapshot"); } +/// A session saved by a build with larger review limits restores with them clamped. Its saved +/// batches still hold the value past the limits, so a resuming client catches up with the +/// snapshot: replaying the log would hand it a change this build refuses. +#[test] +fn a_restored_session_with_clamped_settings_catches_up_by_snapshot() { + use crate::change::{Change, DocProp, Json}; + use figcraft_doc::{DesignReview, MAX_RADII}; + + let mut s = Server::new(base(), "tok", Limits::default()); + let mut a = join(&mut s); + // `b` joined but misses the review batch: it resumes from the log, which is where the old + // build's over-limit value still sits. + let mut b = join(&mut s); + let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap(); + let out = s.receive(a.id(), m); + deliver(&mut a, &out); + b.disconnect(); + let mut state = s.state().unwrap(); + assert_eq!(state.log.len(), 1, "the review batch is in the log"); + + // An older build wrote more radii than this one keeps, in the snapshot and in the batch. + let wide = DesignReview { grid: 8.0, radii: (0..MAX_RADII + 8).map(|i| i as f64).collect(), ..Default::default() }; + let value = Json::of(&wide).unwrap(); + for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) { + if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c { + *v = value.clone(); + } + } + + let mut restored = Server::restore(state, "tok", Limits::default()).unwrap(); + assert_eq!(restored.document().design_review.radii.len(), MAX_RADII, "the snapshot keeps what fits"); + let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() }; + let (id, out) = restored.join(h).unwrap(); + assert_eq!(id, b.id(), "a reconnecting client keeps its id"); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Snapshot(_), .. })), + "a clamped session hands out the snapshot, not a batch past the limits: {out:?}" + ); + deliver(&mut b, &out); + assert_eq!(b.seq(), restored.seq()); + assert_eq!(b.document().design_review.radii.len(), MAX_RADII, "the client takes what the session has"); + // The client that already had the batch catches up with the same snapshot, so both sides + // agree on the clamped value. + let ClientMsg::Hello(h) = a.reconnect(hello()) else { panic!() }; + let (_, out) = restored.join(h).unwrap(); + deliver(&mut a, &out); + assert_eq!(a.document(), b.document()); +} + +/// The same fixture inside the limits keeps resuming from the log: the snapshot catch-up above is +/// for settings this build had to change, not for review settings as such. +#[test] +fn a_restored_session_within_the_limits_resumes_from_the_log() { + use crate::change::{Change, DocProp, Json}; + use figcraft_doc::DesignReview; + + let mut s = Server::new(base(), "tok", Limits::default()); + let mut a = join(&mut s); + let mut b = join(&mut s); + let m = edit(&mut a, |d| d.design_review.grid = 8.0).unwrap(); + let out = s.receive(a.id(), m); + deliver(&mut a, &out); + b.disconnect(); + let mut state = s.state().unwrap(); + let narrow = DesignReview { grid: 8.0, radii: (0..20).map(|i| i as f64).collect(), ..Default::default() }; + let value = Json::of(&narrow).unwrap(); + for c in state.snapshot.iter_mut().chain(state.log.iter_mut().flat_map(|a| a.changes.iter_mut())) { + if let Change::SetDoc { prop: DocProp::DesignReview, value: v } = c { + *v = value.clone(); + } + } + + let mut restored = Server::restore(state, "tok", Limits::default()).unwrap(); + assert_eq!(restored.document().design_review.radii.len(), 20, "the snapshot needs no clamping"); + let ClientMsg::Hello(h) = b.reconnect(hello()) else { panic!() }; + let (_, out) = restored.join(h).unwrap(); + assert!( + matches!(&out[0], Outgoing::To(_, ServerMsg::Welcome { catch_up: CatchUp::Delta(_), .. })), + "a session that needed no clamping resumes from its log: {out:?}" + ); + deliver(&mut b, &out); + assert_eq!(b.seq(), restored.seq()); + assert_eq!(b.document().design_review.radii.len(), 20); +} + #[test] fn resume_needs_the_issued_secret() { let mut s = Server::new(base(), "tok", Limits { max_peers: 2, ..Limits::default() }); diff --git a/crates/collab/src/replica.rs b/crates/collab/src/replica.rs index b7cfb2752..eee844eb5 100644 --- a/crates/collab/src/replica.rs +++ b/crates/collab/src/replica.rs @@ -72,22 +72,24 @@ impl Replica { /// Rebuild a replica from a [`snapshot`](Self::snapshot). pub fn from_snapshot(changes: &[Change]) -> Result { - Self::from_snapshot_leaving_out(changes).map(|(r, _)| r) + Self::from_snapshot_leaving_out(changes).map(|(r, _, _)| r) } /// [`from_snapshot`](Self::from_snapshot), and how many image entries it left out: a /// snapshot saved before the image checks may hold one they refuse, and opens without it. /// Review settings past the current limits are clamped to them, not dropped (see - /// [`docprops::clamp_snapshot_design_review`]). - pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize), Error> { + /// [`docprops::clamp_snapshot_design_review`]); the last value says whether that happened, + /// because a session whose settings had to be clamped can no longer replay its saved batches + /// for clients that resume (they hold the value past the limits). + pub(crate) fn from_snapshot_leaving_out(changes: &[Change]) -> Result<(Replica, usize, bool), Error> { let mut r = Replica { doc: Document::without_pages(""), positions: Positions::new() }; let mut changes = changes.to_vec(); - docprops::clamp_snapshot_design_review(&mut changes); + let clamped = docprops::clamp_snapshot_design_review(&mut changes); let left_out = r.apply_kept(&mut changes, Change::is_image)?; if r.doc.pages.is_empty() { return Err(Error::Invalid("a snapshot needs a page".into())); } - Ok((r, left_out)) + Ok((r, left_out, clamped)) } /// Apply `changes` strictly. When they don't apply together — history written under older diff --git a/crates/collab/src/server.rs b/crates/collab/src/server.rs index 58ad309bb..638491aaf 100644 --- a/crates/collab/src/server.rs +++ b/crates/collab/src/server.rs @@ -175,7 +175,7 @@ impl Server { /// reconnect with their ids). A log that doesn't lead up to the sequence number is dropped /// (clients then catch up with a snapshot). pub fn restore(state: SessionState, token: impl Into, limits: Limits) -> Result { - let (replica, left_out) = Replica::from_snapshot_leaving_out(&state.snapshot)?; + let (replica, left_out, review_clamped) = Replica::from_snapshot_leaving_out(&state.snapshot)?; let mut server = Server::new(replica.document().clone(), token, limits); server.state = replica; server.session = state.session; @@ -195,9 +195,11 @@ impl Server { // History saved before the image checks may hold image entries they refuse. The snapshot // opens without them, and a saved log putting images may give a resuming client other // bytes under a key it holds, which this state can't check: either way resuming clients - // catch up with the snapshot. + // catch up with the snapshot. The same holds for review settings this build had to clamp: + // a saved batch still carries the value past the limits, and a resuming client would + // refuse it, so the clamped snapshot is what everyone catches up with. let puts_images = state.log.iter().flat_map(|a| &a.changes).any(Change::is_image); - server.resync = left_out > 0 || puts_images; + server.resync = left_out > 0 || puts_images || review_clamped; if contiguous && state.log.last().is_none_or(|a| a.seq == state.seq) { for a in state.log { server.remember(a); From 04ff77c5b6b281e5db42d5d227eeb95407a4ced9 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:26:30 +0800 Subject: [PATCH 16/57] M13: a gate naming a rule the file skips fails unless it allows the skip --- crates/engine/src/design/audit.rs | 10 +++++++++ crates/engine/src/design/mod.rs | 22 ++++++++++++++++++- crates/engine/src/design/tests.rs | 35 +++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/design/audit.rs b/crates/engine/src/design/audit.rs index 5045aee52..7c03ae3cb 100644 --- a/crates/engine/src/design/audit.rs +++ b/crates/engine/src/design/audit.rs @@ -373,6 +373,16 @@ pub(crate) fn run( } } } + // A gate that names a rule the file turned off, or that its preset leaves out, asks for a + // check the run does not do: named here, so the gate can refuse instead of passing on + // evidence it never gathered. Only explicitly named rules count — a run without a filter is + // the review under the file's own settings, the file's choice. + for id in filter.into_iter().flatten() { + if !settings.enabled(id) { + let reason = if settings.disabled.contains(id.as_str()) { "disabled" } else { "preset" }; + unchecked.push(json!({"rule": id, "reason": reason})); + } + } let mut out = settings.json(); if let Some(o) = out.as_object_mut() { o.insert("scope".into(), json!(scope)); diff --git a/crates/engine/src/design/mod.rs b/crates/engine/src/design/mod.rs index f4d308cf5..58ef50afa 100644 --- a/crates/engine/src/design/mod.rs +++ b/crates/engine/src/design/mod.rs @@ -44,7 +44,7 @@ pub fn specs() -> Vec { spec!( "design.assert", "Assert design", - "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit could not check a rule it asked for (truncated at the node limit it ran with, or past a measure cap: what it did not reach is unchecked, so narrow the scope, filter the rules or raise `limit`); read-only, for CI", + "{scope?: selection|page|document (default: selection when something is selected, else page), ids?: [layer ids] (instead of scope), rules?: [rule ids], preset?: recommended|strict|accessibility (default: the file's), modes?: {collection: mode} (resolve bound colours in these variable modes), failOn?: low|medium|high (default high), minScore?: 0-100 (default 0), limit?: 1000-1000000 (nodes before the audit says truncated; default 50000), allowSkipped?: bool (default false; passes a gate naming a rule the file disables or its preset excludes — never a truncated audit or a measure cap)} → {ok: true, score, counts} fails with an error when a finding at or above failOn exists, the score is below minScore, or the audit could not check a rule it asked for (truncated at the node limit it ran with, past a measure cap, or skipped by the file's settings: what it did not reach is unchecked, so narrow the scope, filter the rules or raise `limit`); read-only, for CI", false, assert_cmd ), @@ -138,6 +138,26 @@ fn assert_cmd(s: &mut Session, p: &Value) -> Result { "design review failed: the audit stopped at the {limit}-node limit after {nodes} nodes, so what it did not reach is unchecked; audit a smaller scope (selection, page or ids) or raise `limit`, then assert again" ))); } + // A gate naming a rule the file disabled or its preset leaves out is asking for a check the + // run does not do: refused, unless the caller passes `allowSkipped` to accept exactly that — + // it does not waive a truncated audit or a measure cap, which stay unchecked evidence. + let allow_skipped = params::boolean(p, "allowSkipped").unwrap_or(false); + let skipped: Vec<&str> = report["unchecked"] + .as_array() + .map(|v| { + v.iter() + .filter(|e| matches!(e["reason"].as_str(), Some("disabled") | Some("preset"))) + .filter_map(|e| e["rule"].as_str()) + .filter(|rule| filter.as_ref().is_none_or(|set| set.contains(*rule))) + .collect() + }) + .unwrap_or_default(); + if !skipped.is_empty() && !allow_skipped { + return Err(EngineError::Other(format!( + "design review failed: the file's settings skip {} (disabled by the file, or not in the preset it checks with), so a gate naming it checked nothing for it; check the file's design.configure, gate with a preset that includes it, or pass allowSkipped to accept the skip", + skipped.join(", ") + ))); + } // What the audit reported as unchecked, restricted to the rules this gate asked for. The // audit names each rule it could not check (`limit` truncation is handled above with its own // advice), so a cap added there fails this gate without a list here to keep in step. diff --git a/crates/engine/src/design/tests.rs b/crates/engine/src/design/tests.rs index b01242b4b..65787ed3e 100644 --- a/crates/engine/src/design/tests.rs +++ b/crates/engine/src/design/tests.rs @@ -899,6 +899,41 @@ fn assert_refuses_a_scope_whose_measured_checks_were_capped() { assert!(s.execute("design.assert", &json!({"scope": "page"})).is_ok(), "a disabled rule leaves nothing unchecked"); } +#[test] +fn a_gate_naming_a_rule_the_file_skips_fails_unless_allowed() { + let mut s = Session::new(); + ex(&mut s, "shape.rectangle", json!({"x": 0.0, "y": 0.0, "width": 10.0, "height": 10.0})); + // The file turns the clipping rule off; naming it asks for a check the run does not do. + ex(&mut s, "design.configure", json!({"disabled": ["layout.clipped"]})); + let named = json!(["layout.clipped"]); + let audit = ex(&mut s, "design.audit", json!({"scope": "page", "rules": &named})); + assert_eq!(audit["unchecked"][0], json!({"rule": "layout.clipped", "reason": "disabled"}), "{audit}"); + let err = s.execute("design.assert", &json!({"scope": "page", "rules": &named})).unwrap_err().to_string(); + assert!(err.contains("the file's settings skip layout.clipped"), "{err}"); + // Deliberately allowing the skip passes, and the file's own whole review still passes + // without naming the rule — that is the file's choice, not the gate's. + assert!(s.execute("design.assert", &json!({"scope": "page", "rules": &named, "allowSkipped": true})).is_ok()); + assert!(s.execute("design.assert", &json!({"scope": "page"})).is_ok()); + // The same through the preset: `layout.no-auto-layout` is Strict-only. + let strict_only = json!(["layout.no-auto-layout"]); + let err = s.execute("design.assert", &json!({"scope": "page", "rules": &strict_only})).unwrap_err().to_string(); + assert!(err.contains("the file's settings skip layout.no-auto-layout"), "{err}"); + assert!(s.execute("design.assert", &json!({"scope": "page", "rules": &strict_only, "preset": "strict"})).is_ok()); + // The allowance never waives unchecked evidence: on a scope whose measured checks were + // capped, `allowSkipped` still fails on the cap. + for i in 0..2_001 { + ex( + &mut s, + "text.create", + json!({"text": "Overflowing line of interface copy", "name": &format!("Box {i}"), "x": 0.0, "y": 0.0, + "width": 60, "props": {"textAutoResize": "none"}}), + ); + } + let both = json!(["layout.clipped", "layout.text-overflow"]); + let err = s.execute("design.assert", &json!({"scope": "page", "rules": &both, "allowSkipped": true})).unwrap_err().to_string(); + assert!(err.contains("did not measure all of layout.text-overflow"), "{err}"); +} + #[test] fn assert_refuses_an_explicit_empty_selection() { let mut s = Session::new(); From 8a77266f84c9b0487567ea32eda12442a8ed3941 Mon Sep 17 00:00:00 2001 From: phonedu <135960865+phonedu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:26:30 +0800 Subject: [PATCH 17/57] M13: sharing refuses a file whose review settings pass the limits --- crates/collab-net/src/host.rs | 10 ++++++++ crates/collab-net/src/loopback_tests.rs | 33 +++++++++++++++++++++++++ crates/doc/src/design_review.rs | 14 +++++++++++ crates/engine/src/live_share_tests.rs | 23 +++++++++++++++++ crates/engine/src/sharing/live/host.rs | 20 +++++++++++++++ docs/collab-protocol.md | 4 ++- 6 files changed, 103 insertions(+), 1 deletion(-) diff --git a/crates/collab-net/src/host.rs b/crates/collab-net/src/host.rs index c7180708c..6d51a051c 100644 --- a/crates/collab-net/src/host.rs +++ b/crates/collab-net/src/host.rs @@ -84,6 +84,16 @@ impl Host { if cfg.view_token.as_deref().is_some_and(|v| same_secret(v, &cfg.token)) { return Err(io::Error::other("the view-only secret is the same as the edit secret")); } + // The file's review settings stay inside the limits this build keeps: clients apply every + // arriving value against them, so a file past them (written by an older or looser build) + // would break everyone who joins. The host trims them first (`design.configure`). + let over = cfg.doc.design_review.over_limits(); + if !over.is_empty() { + let list = over.iter().map(|(what, have, max)| format!("{have} {what} (this build keeps at most {max})")).collect::>().join(", "); + return Err(io::Error::other(format!( + "this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again" + ))); + } let listener = match TcpListener::bind(cfg.addr) { Ok(l) => l, Err(e) if e.kind() == io::ErrorKind::AddrInUse && cfg.any_port_if_taken => TcpListener::bind(SocketAddr::new(cfg.addr.ip(), 0))?, diff --git a/crates/collab-net/src/loopback_tests.rs b/crates/collab-net/src/loopback_tests.rs index dadda9ef4..7af598bf9 100644 --- a/crates/collab-net/src/loopback_tests.rs +++ b/crates/collab-net/src/loopback_tests.rs @@ -290,6 +290,39 @@ fn a_view_token_lets_people_look_and_not_edit() { host.stop(); } +/// A file whose review settings are past this build's limits is not hosted: joining clients +/// would refuse the value when it reaches them. The error names the lists and the way out. +#[test] +fn a_file_with_review_settings_past_the_limits_is_not_shared() { + use figcraft_doc::{DesignReview, MAX_DISABLED, MAX_RADII}; + + let probe = Probe::new(); + let mut doc = Document::new("Shared file"); + doc.repair(); + doc.design_review = DesignReview { + radii: (0..MAX_RADII + 1).map(|i| i as f64).collect(), + disabled: (0..MAX_DISABLED + 1).map(|i| format!("rule.{i}")).collect(), + ..Default::default() + }; + let cfg = HostConfig { + addr: SocketAddr::from(([127, 0, 0, 1], 0)), + any_port_if_taken: false, + file: FILE.into(), + token: TOKEN.into(), + view_token: None, + doc, + name: "Hana".into(), + limits: fast_limits(), + core: Limits::default(), + }; + let e = Host::start(cfg, probe.inbox.clone()).err().expect("settings past the limits are refused"); + let text = e.to_string(); + assert!(text.contains("can't be shared"), "{text}"); + assert!(text.contains(&format!("{} corner radii (this build keeps at most {MAX_RADII})", MAX_RADII + 1)), "{text}"); + assert!(text.contains(&format!("{} disabled rules", MAX_DISABLED + 1)), "{text}"); + assert!(text.contains("design.configure"), "{text}"); +} + #[test] fn unreachable_hosts_fail_at_once() { // A port nothing listens on. diff --git a/crates/doc/src/design_review.rs b/crates/doc/src/design_review.rs index 002fe6d53..9aefbbff6 100644 --- a/crates/doc/src/design_review.rs +++ b/crates/doc/src/design_review.rs @@ -82,6 +82,20 @@ impl DesignReview { pub fn grid(&self) -> f64 { if self.grid.is_finite() && (GRID_MIN..=GRID_MAX).contains(&self.grid) { self.grid } else { 4.0 } } + + /// The lists that hold more than this build keeps, as `(what, how many, the cap)`. Sharing a + /// file with any of these is refused (`collab.share`), an arriving edit is refused + /// (`figcraft_collab`), and a saved snapshot opens with what fits instead. + pub fn over_limits(&self) -> Vec<(&'static str, usize, usize)> { + [ + ("corner radii", self.radii.len(), MAX_RADII), + ("brand colours", self.brand.len(), MAX_BRAND_COLORS), + ("disabled rules", self.disabled.len(), MAX_DISABLED), + ] + .into_iter() + .filter(|(_, have, max)| have > max) + .collect() + } } #[cfg(test)] diff --git a/crates/engine/src/live_share_tests.rs b/crates/engine/src/live_share_tests.rs index 9c86e0900..9581dc3fa 100644 --- a/crates/engine/src/live_share_tests.rs +++ b/crates/engine/src/live_share_tests.rs @@ -471,3 +471,26 @@ fn joining_takes_a_code_of_either_kind_or_a_link() { assert_eq!((&r["status"], &r["reason"]), (&json!("failed"), &json!("No session with that code"))); assert_eq!(s.message.as_deref(), Some("No session with that code")); } + +/// A file whose review settings are past this build's limits is not shared, hosted or published: +/// joining clients apply arriving values against the limits they were built with, so a file +/// written by a looser build would break them. Nothing reaches the link; the error names the +/// lists and the way out. +#[test] +fn a_file_past_the_review_limits_is_not_shared() { + use figcraft_doc::{DesignReview, MAX_RADII}; + + let mut s = Session::new(); + s.doc_mut().unwrap().design_review = DesignReview { radii: (0..MAX_RADII + 1).map(|i| i as f64).collect(), ..Default::default() }; + for (cmd, p) in [ + ("collab.host", json!({})), + ("collab.share", json!({"via": "local"})), + ("collab.share", json!({"via": "online", "server": "wss://s.example/"})), + ("collab.publish", json!({"server": "wss://s.example/"})), + ] { + let e = err(&mut s, cmd, p); + assert!(e.contains("can't be shared"), "{cmd}: {e}"); + assert!(e.contains(&format!("{} corner radii (this build keeps at most {MAX_RADII})", MAX_RADII + 1)), "{cmd}: {e}"); + assert!(e.contains("design.configure"), "{cmd}: {e}"); + } +} diff --git a/crates/engine/src/sharing/live/host.rs b/crates/engine/src/sharing/live/host.rs index 916da6949..417667abe 100644 --- a/crates/engine/src/sharing/live/host.rs +++ b/crates/engine/src/sharing/live/host.rs @@ -36,6 +36,24 @@ pub(super) fn unavailable(cmd: &str) -> EngineError { ) } +/// A file whose review settings are past this build's limits can't be shared or published: +/// every joining client applies arriving values against the limits it was built with, so a file +/// written by an older or looser build would break them (and no build silently trims what the +/// file's author set). The error names the lists and the way out. +fn check_sharable(cmd: &str, doc: &figcraft_doc::Document) -> Result<()> { + let over = doc.design_review.over_limits(); + if over.is_empty() { + return Ok(()); + } + let list = over.iter().map(|(what, have, max)| format!("{have} {what} (this build keeps at most {max})")).collect::>().join(", "); + Err(bad( + cmd, + format!( + "this file can't be shared: its design review settings hold {list}; trim them with design.configure (or reset the settings), then share again" + ), + )) +} + /// `collab.host`: host the open file (on this machine unless `p` says where) with an invite link. pub(super) fn host(s: &mut Session, p: &Value) -> Result { start_host(s, "collab.host", p, Bind::Local, false, false)?; @@ -57,6 +75,7 @@ fn start_host(s: &mut Session, cmd: &str, p: &Value, bind: Bind, short: bool, vi Some(other) => other.parse::().map(Bind::Addr).map_err(|_| bad(cmd, "`bind` must be \"local\", \"lan\" or an IP address"))?, }; let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?; + check_sharable(cmd, &doc)?; let opts = HostOptions { port, bind, name: display_name(&s.prefs), doc, short, view }; let (id, info) = s.live.start(cmd, |l, id| l.host(id, opts).map_err(|e| EngineError::Other(format!("couldn't start the live session: {e}"))))?; s.live.open(Live { id, status: Status::Live, info: Some(info), doc_uid: Some(uid), tab: Some(uid), ..Live::default() }); @@ -75,6 +94,7 @@ pub(super) fn publish(s: &mut Session, p: &Value) -> Result { fn start_publish(s: &mut Session, cmd: &str, server: &str, p: &Value, share: bool) -> Result { let key = string(p, "key").map(|k| k.trim().to_string()).filter(|k| !k.is_empty()); let (doc, uid) = s.ds().map(|ds| (ds.doc.clone(), ds.uid))?; + check_sharable(cmd, &doc)?; let name = string(p, "name").map(|n| n.trim().chars().filter(|c| !c.is_control()).take(256).collect::()).filter(|n| !n.is_empty()); let me = display_name(&s.prefs); let opts = PublishOptions { server: server.trim().to_string(), key, name: name.unwrap_or_else(|| doc.name.clone()), me, doc, share }; diff --git a/docs/collab-protocol.md b/docs/collab-protocol.md index 6cada9a59..8090f0fa7 100644 --- a/docs/collab-protocol.md +++ b/docs/collab-protocol.md @@ -153,7 +153,9 @@ As built: `design-review`; a client that doesn't gets every batch, catch-up delta and snapshot without them, and an accepted batch still reaches it when nothing of it is left, so sequence numbers never skip; a snapshot saved with longer lists opens clamped to the limits `design.configure` - keeps) and library data (whole values); styles, + keeps, and a session restored from such a snapshot catches every resuming client up with that + snapshot, since its saved batches still hold the value past the limits; a host refuses to share + a file whose settings are already past the limits) and library data (whole values); styles, comment threads, variable collections and variables (one entry per id plus the order of ids; the whole list when ids aren't unique); dev-mode snapshots (per layer); images (per content hash, the encoded bytes as base64; as an entry applies the claim is checked: every key is From d23c8b645661fef7d0e156bcc230ab2ae1e9ebe0 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Wed, 18 Nov 2026 22:09:07 +0100 Subject: [PATCH 18/57] M8: Code Connect for agents MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A link can say where the code component lives (`source`, a path inside the repository), what a property's design values are called in code (`values`: {"State": {"Hover": "hovered"}} renders `hovered`; a value without an entry keeps its design name) and `notes`, through codeConnect.set, the connect file and Inspect ▸ Connect to code (a Source file field and a row per variant value). The fields are skipped when empty, so existing files and exports don't change. codeConnect.list and the MCP tool component_mappings say which code component each design component is: import line, name, ready snippet, properties and variants, and with a repository root whether each source file is there. sync_mappings imports or exports a repository's connect file. codeConnect.export {path} keeps the file's other top-level keys and the links of components this design doesn't have, so several designs can share one file. --- ROADMAP.md | 1 + crates/doc/src/node.rs | 9 ++ crates/engine/src/code_connect_tests.rs | 121 ++++++++++++++++ crates/engine/src/dev/code_connect.rs | 174 ++++++++++++++++++++++-- crates/mcp/src/tools.rs | 53 ++++++++ crates/mcp/tests/it/code_connect.rs | 37 +++++ crates/mcp/tests/it/main.rs | 2 + crates/ui-egui/locales/en.toml | 3 + crates/ui-egui/src/panels/dev_mode.rs | 48 +++++++ docs/mcp.md | 16 ++- 10 files changed, 447 insertions(+), 17 deletions(-) create mode 100644 crates/mcp/tests/it/code_connect.rs diff --git a/ROADMAP.md b/ROADMAP.md index 2286b0c6e..cbd89bc8d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -367,6 +367,7 @@ Ranked; detail and milestones in [`docs/roadmap.md`](docs/roadmap.md). | Date | Change | Summary | |---|---|---| | 2026-11-18 | minor | M8: design context for AI agents. `inspect.designContext` and the MCP tool `design_context` read the selection (or `ids`, or a `scope`) in one call: a tree where each layer keeps apart `explicit` values, `derived` ones layout worked out and `unsupported` ones with no direct CSS equivalent, joined with the variables (every mode's stored and resolved value), styles, components, fonts and assets it uses, and what the design leaves `missing`. A connected instance gives its code instead of its layers, and a result that wouldn't fit the client asks for fewer layers. Numbers unchanged | +| 2026-11-19 | minor | M8: Code Connect for agents. A link can name its source file, what variant values are called in code (Primary becomes `primary` in the snippet) and notes, in the Inspect tab, `codeConnect.set` and `figcraft.connect.json`. `codeConnect.list` and the MCP tool `component_mappings` say which code component each design component is, and whether its source file exists; `sync_mappings` imports and exports a repository's file. `codeConnect.export {path}` keeps the file's other keys and the links of components the design doesn't have, so several designs can share one file. Numbers unchanged | | 2026-11-18 | minor | M3, gap 10: library analytics count insertions and detachments of styles and variables. Applying one, or copying or duplicating content that uses it, inserts it; the Detach button detaches it; an instance counts as its component alone. Show usage and `library.usage` give them per style and variable over the chosen period. Modes aren't counted. Numbers unchanged. Tests: `library_asset_counts_tests`, `library_assets_tests`. | | 2026-11-18 | minor | M9, gap 6: the browser build uses team libraries and plugin directories on a server, through its WebSocket requests: adding a library by its link, its styles and components, publishing to it, Show usage and the reports a file sends; browsing a directory and installing from it, for the page only. Scripts through `window.figcraft` still can't, as commands there don't wait for the server. Numbers unchanged. Tests: `exchange_tests`. | | 2026-11-17 | minor | M6: Android Vector Drawable XML serialization uses the shared writer; application projection and colour policy remain local. Byte-parity tests cover full documents and generated deep wrappers; no new format capability or incumbent certification. | diff --git a/crates/doc/src/node.rs b/crates/doc/src/node.rs index bea172277..650966626 100644 --- a/crates/doc/src/node.rs +++ b/crates/doc/src/node.rs @@ -250,6 +250,15 @@ pub struct CodeLink { pub name: String, /// The snippet with `{property}` and `{property ? "a" : "b"}` placeholders. pub template: String, + /// Where the code component lives, relative to the code repository. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub source: String, + /// What a property's design values are called in code: property → design value → code value. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub values: BTreeMap>, + /// Notes for whoever uses the component. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub notes: String, } /// A dev resource: a link for developers attached to a layer. The URL is data only: it is shown diff --git a/crates/engine/src/code_connect_tests.rs b/crates/engine/src/code_connect_tests.rs index 4474fe03a..9750db813 100644 --- a/crates/engine/src/code_connect_tests.rs +++ b/crates/engine/src/code_connect_tests.rs @@ -298,3 +298,124 @@ fn many_entries_for_one_component_each_link() { let i = idv(&ex(&mut s, "instance.create", json!({"component": hover, "x": 0, "y": 500}))); assert_eq!(code(&mut s, i, "react"), "", 3) { edit = Some(("template", v)); } widgets::note(ui, tr("{property} is its value; {property ? \"a\" : \"b\"} picks a string. Other {…} stays as written."), t.text_secondary); + variant_values(app, ui, doc, owner, lang, &link); if let Some((key, value)) = edit { let mut params = params; params[key] = json!(value); @@ -499,6 +509,44 @@ pub fn connect_section(app: &mut FigApp, ui: &mut Ui, doc: &Document, id: NodeId ui.add_space(4.0); } +/// The variant values of a connected component and what code calls them: a value left empty +/// stays as the design names it. +fn variant_values(app: &mut FigApp, ui: &mut Ui, doc: &Document, owner: NodeId, lang: CodeLang, link: &CodeLink) { + let properties = code_connect::variants(doc, owner); + if properties.is_empty() { + return; + } + let mut change: Option<(String, String, String)> = None; + widgets::sublabels(ui, tr("Variant value"), Some(tr("In code"))); + let col = widgets::col_width(ui.available_width()); + for (property, options) in &properties { + for option in options { + let current = link.values.get(property).and_then(|m| m.get(option)).map_or("", String::as_str); + row(ui, 32.0, |ui| { + ui.spacing_mut().item_spacing.x = 8.0; + ui.allocate_ui_with_layout(vec2(col, 24.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(col); + ui.add(egui::Label::new(format!("{property}: {option}")).truncate()); + }); + if let Some(v) = widgets::text_field(ui, Id::unique(("code_connect_value", owner, lang.id(), property, option)), current, col, option) + { + change = Some((property.clone(), option.clone(), v)); + } + }); + } + } + let Some((property, option, value)) = change else { return }; + let mut values = link.values.clone(); + let mapped = values.entry(property).or_default(); + if value.trim().is_empty() { + mapped.remove(&option); + } else { + mapped.insert(option, value.trim().to_string()); + } + values.retain(|_, m| !m.is_empty()); + app.run("codeConnect.set", json!({"id": owner, "language": lang.id(), "values": values})); +} + /// Dev Mode plugins: the installed plugins that only read the document, run from the Inspect tab. pub fn plugins_section(app: &mut FigApp, ui: &mut Ui) { let runnable: Vec<(String, String, String)> = app diff --git a/docs/mcp.md b/docs/mcp.md index c1f3992a9..b2aba1f43 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -409,6 +409,8 @@ a later step can use `{"$step": 0, "field": "ids/0"}` to target the first match. | `inspect_document {depth, allPages, fields?, outline?}` | The document as JSON (its `id`, layer tree, styles, selection, history); `fields` selects layer properties, `outline: true` gives a compact tree (below). The tools that act on a document also take `document` (see Naming the document below). | | `get_node {id, depth, fields?, outline?}` | One layer as JSON; takes the same `fields` and `outline` options; `pluginData` (`{key: value}`, values as strings) when the layer or page has layer data written with `set_properties {props: {pluginData}}`. | | `design_context {ids?, scope?, depth?, maxNodes?, maxBytes?}` | Everything needed to build a design in one read: see [Design context](#design-context). | +| `component_mappings {ids?, unmapped?, root?}` | Which code component each design component is: `import`, `name`, `source` (and `sourceFound` under `root`, default the server's folder), a ready `snippet`, `properties` with variants, and `values` that need translating. | +| `sync_mappings {direction, path?}` | Apply a code repository's `figcraft.connect.json` to the open design (`import`) or write the design's mappings to it (`export`); `path` defaults to that file in the server's folder. | | `select {ids}` | Replace the selection (`[]` deselects). | | `export {ids, format, scale \| size, path?, bleed?, cropMarks?, bleedMarks?, cmyk?, contentsOnly?, includeBoundingBox?, svgOutlineText?, svgIdAttribute?, svgSimplifyStroke?, vdCompat?, colorProfile?, quality?}` | png, jpg, svg, webp, pdf, xml (an Android Vector Drawable: `svgIdAttribute` writes `android:name`, `vdCompat` is `bestEffort` (default: approximated with a warning), `exact` (left out with a warning) or `ignore` (no warnings: overlapping layer opacity dropped, even-odd fills kept as `fillType="evenOdd"`, diamond gradients left out), and the result lists `warnings` for what was changed or left out), or `fig`: the whole file as `.fig`, experimental (see Exporting `.fig` files below); `size` is `2x`, `512w` or `512h`; `quality` is the JPG quality, 1 to 100 (default 90). The image covers what the layers paint (shadows towards their offset, strokes, unclipped children, a mask group's mask; hidden layers take no room; a slice is its area with everything under it, or only the frame or group it sits in while `contentsOnly` is on); `contentsOnly: false` also draws every other layer showing in that area, `includeBoundingBox` exports the layers' own boxes; SVG: `svgOutlineText: false` keeps ``, `svgIdAttribute` writes unique ids from layer names, `svgSimplifyStroke: false` writes every stroke as an outline; png, jpg and webp: `colorProfile` is `sameAsFile` (default: the document's profile), `srgb` or `displayP3`, the pixels converted (out-of-gamut colors clip) and the file tagged for it (PNG: `sRGB` chunk, or ICC and `cICP` for Display P3; JPG: ICC profile; WebP: ICC profile for Display P3, none for sRGB) (SVG, XML and RGB PDF output are always sRGB; PDF with `cmyk` is DeviceCMYK). The same options go in export settings (`export.add` / `export.update`). PDF: frames one page each (sized in points), anything else together on one page; print options: `bleed` (points or a length like `"3mm"`, `"0.125in"`), crop and bleed marks, CMYK colour (see Exports below), also taken by `file.export`, `file.exportLayers`, `file.exportFramesPdf` and stored per export setting by `export.add` / `export.update`; `run_command` `file.exportFramesPdf {page?, path?}` writes every top-level frame of a page. Without `path`, images come back as MCP image content, SVG as text, XML as text followed by `{format, bytes, warnings}`. Layers' own export settings: `run_command` with `export.add` / `export.update {index, size?, suffix?, format?}` / `export.remove` and `file.exportLayers {ids?, dir?, assets?}` (every layer once per setting, named `.`, a slash in a layer name making a folder; `assets: true` exports the Inspect tab's assets instead: icons as SVG, images as PNG). | | `screenshot {ids?, scale?, maxSize?, window?}` | PNG of the page (with background) or of layers, scaled to fit `maxSize` (default 1600). `window: true` captures the app window in front when attached, a window id (see Windows below) that window. | @@ -1860,11 +1862,19 @@ permissions: without it nothing is downloaded); `plugin.directory.publish {path `@acme/ui` gives `import { Button } from "@acme/ui";` then ``. `codeConnect.remove {id?, language?}` (no language: all). `codeConnect.export {path?}` → `{text, links}` (or writes the file): `{version: 1, links: [{component, language, - importPath, name, template}]}`, sorted, meant to live in the code repository as - `figcraft.connect.json`; `codeConnect.import {json | path}` → `{linked, warnings}` links each + importPath, name, template, source?, values?, notes?}]}`, sorted, meant to live in the code + repository as `figcraft.connect.json` (writing a file that's there keeps its other top-level keys + and the links of components this design doesn't have, so several designs can share one file); `codeConnect.import {json | path}` → `{linked, warnings}` links each entry to every component or set with that name (one undo step; at most 5,000 links and 4 MB; templates up to 4,000 characters, names 100, import paths 300; invalid entries are skipped with a - warning). `get_node` lists a component's links as `codeLinks`. In the app, the Inspect tab's + warning). A link can also say where the code component lives (`source`, a path inside the + repository), what a property's design values are called in code (`values`: + `{"Variant": {"Primary": "primary"}}`, so `{Variant}` renders `primary`; a value without an entry + keeps its design name) and `notes`, through `codeConnect.set`, the file and the Inspect tab. + `codeConnect.list {ids?, unmapped?, root?}` → `{components: [{id, name, type, mapped, properties, + links: [{language, importPath, import, name, template, snippet, source?, sourceFound?, values?, + notes?}]}], mapped, unmapped}` answers which code component each design component is; with `root` + it says whether each `source` exists there. `get_node` lists a component's links as `codeLinks`. In the app, the Inspect tab's Connect to code section edits them in the Code section's language, with a live preview and a Connected badge. An editor extension isn't needed: agents and editors read the same snippets through this server. Plugins whose manifest asks only for `read` also run from the Inspect tab, From dbccabce4170dfe1479a3f9469a93082b7719739 Mon Sep 17 00:00:00 2001 From: B-uchi Date: Thu, 19 Nov 2026 01:54:50 +0100 Subject: [PATCH 19/57] M8: design context gives Code Connect links as the connect file does `inspect.designContext` wrote a component's links through `camel`, which renames keys at every depth, so a mapped design value such as `extra_large` came out as `extraLarge`. Its components and the code it gives each connected layer now use Code Connect's own link JSON: value names stay as written, and the code carries the link's `source` and `notes`. Export also sorts its links once, after merging the file's other links. --- crates/engine/src/design_context_tests.rs | 26 +++++++++++++++++++++++ crates/engine/src/dev/code_connect.rs | 16 ++++++++------ crates/engine/src/dev/design_context.rs | 11 ++++++++-- docs/mcp.md | 2 +- 4 files changed, 46 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/design_context_tests.rs b/crates/engine/src/design_context_tests.rs index 5d6f51304..722edc8b4 100644 --- a/crates/engine/src/design_context_tests.rs +++ b/crates/engine/src/design_context_tests.rs @@ -407,3 +407,29 @@ fn a_join_stopped_at_its_budget_says_so() { let (some, complete) = crate::design_context::referenced(s.doc().unwrap(), &start, &none, 3); assert_eq!((some.len(), complete), (3, false), "{some:?}"); } + +#[test] +fn code_links_keep_their_value_names_and_carry_source_and_notes() { + let mut s = session(); + let variants: Vec<_> = ["small", "extra_large"] + .iter() + .map(|v| { + let f = node(&mut s, json!({"type": "frame", "name": format!("Size={v}"), "width": 80, "height": 32})); + id(&s.execute("component.create", &json!({"ids": [f]})).unwrap()) + }) + .collect(); + let set = id(&s.execute("component.combineVariants", &json!({"ids": variants})).unwrap()); + s.execute( + "codeConnect.set", + &json!({"id": set, "name": "Button", "template": "