From 152e3b560c28d16500d7f8f7164e6e3572ac1be1 Mon Sep 17 00:00:00 2001 From: cdwilson127 Date: Wed, 11 Nov 2026 08:43:21 +1300 Subject: [PATCH 1/4] MCP: find_text takes `query` as its filter; stylesmanager set replies with what changed (#3011) find_text only knew `contains`; a call with `query` was accepted and the filter silently dropped, so every text came back. The texts command now reads `query` as `contains` (contains wins when both are given), and the tool schema and docs list it. stylesmanager `set` replied with the whole table (255 styles, about 25 kB for a .ctb). It now replies like `new` and `load` do, with the table summary, plus the edited `style` and the `removedStyle` name when given. --- crates/engine/src/cmd/inquiry.rs | 9 ++++++-- crates/engine/src/cmd/layout/plotstyle.rs | 18 +++++++++++++++- crates/engine/tests/it/plot_styles.rs | 26 ++++++++++++++++++++++- crates/mcp/src/tests.rs | 16 ++++++++++++++ crates/mcp/src/tools.rs | 4 ++-- docs/mcp.md | 2 +- 6 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/inquiry.rs b/crates/engine/src/cmd/inquiry.rs index 283551dfd8..82990fadb6 100644 --- a/crates/engine/src/cmd/inquiry.rs +++ b/crates/engine/src/cmd/inquiry.rs @@ -56,7 +56,7 @@ pub fn specs() -> Vec { CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(), CommandSpec::new("loops", "Implied Loops", loops::run).params(loops::PARAMS).noundo(), CommandSpec::new("texts", "Query Texts", run_texts) - .params("{contains?: text (any case), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders") + .params("{contains?: text (any case; `query` is the same filter), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders") .noundo(), CommandSpec::new("countlist", "Count List", count::run_countlist) .params("{space?: all (default)|current|model|, nested?: bool} → per-block counts, as COUNT") @@ -664,7 +664,12 @@ fn run_texts(s: &mut Session, p: &Value) -> Result { v.as_u64().map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| bad(CMD, format!("`{k}` must be a whole number, 0 or more"))) }) }; - let contains = text("contains")?; + // `query` is what agents tend to call the filter; without this alias it was silently ignored + // and every text came back (#3011). + let contains = match text("contains")? { + Some(c) => Some(c), + None => text("query")?, + }; let layer = text("layer")?; let window = given("window") .map(|w| { diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index d432343c2c..8353e68c77 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -264,9 +264,11 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { return Err(bad(cmd, format!("`{name}` has no style `{rm}`"))); } } + let mut changed: Option = None; if let Some(v) = p.get("style") { let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?; + changed = Some(sname.to_string()); let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) { Some(i) => i, None if t.kind == PlotStyleKind::Named => { @@ -283,8 +285,22 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { } } let t = t.sanitized(); - let out = serde_json::to_value(&t).unwrap_or(Value::Null); + // Just what changed, not the whole table (a colour-dependent one has 255 styles): the + // table summary as `new` and `load` reply, the edited style, the removed style's name. + let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n)).and_then(|x| serde_json::to_value(x).ok())); + let removed = str_param(p, "removeStyle").map(str::trim); + let name = t.name.clone(); store(s.doc_mut()?, t); + let d = s.doc()?; + let mut out = table_summary(d, &find_table(cmd, d, &name)?); + if let Some(o) = out.as_object_mut() { + if let Some(e) = edited { + o.insert("style".into(), e); + } + if let Some(r) = removed { + o.insert("removedStyle".into(), json!(r)); + } + } Ok(out) } "delete" => { diff --git a/crates/engine/tests/it/plot_styles.rs b/crates/engine/tests/it/plot_styles.rs index 4ad0922c3e..6b9e27cbc3 100644 --- a/crates/engine/tests/it/plot_styles.rs +++ b/crates/engine/tests/it/plot_styles.rs @@ -62,7 +62,10 @@ fn stylesmanager_creates_edits_saves_and_loads_tables() { &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5", "color": "#00ff00", "screening": 40, "lineweight": 0.35, "linetype": "HIDDEN", "end": "round"}}), ) .unwrap(); - let pen = r["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Pen 5").unwrap().clone(); + // `set` replies with the table summary and the edited style, not the whole table. + assert_eq!(r["styles"], 2); + let pen = r["style"].clone(); + assert_eq!(pen["name"], "Pen 5"); assert_eq!( (pen["color"].as_str(), pen["screening"].as_u64(), pen["lineweight"].as_u64(), pen["end"].as_str()), (Some("#00ff00"), Some(40), Some(35), Some("round")) @@ -131,3 +134,24 @@ fn plot_style_save_is_atomic_and_keeps_permissions() { assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); let _ = std::fs::remove_dir_all(&dir); } + +/// #3011: `set` on a colour-dependent table (255 styles) replies with what changed, not the table. +#[test] +fn stylesmanager_set_replies_with_the_change_not_the_whole_table() { + let mut s = Session::new(); + let set = json!({"action": "set", "name": "monochrome.ctb", "style": {"name": "Color_13", "lineweight": 0.3}}); + let r = s.execute("stylesmanager", &set).unwrap(); + assert_eq!((r["name"].as_str(), r["styles"].as_u64()), (Some("monochrome.ctb"), Some(255)), "{r}"); + assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some("Color_13"), Some(30)), "{r}"); + assert!(r.to_string().len() < 1000, "the reply is short, not the 255-style table: {} bytes", r.to_string().len()); + // The edit is in the drawing. + let got = s.execute("stylesmanager", &json!({"action": "get", "name": "monochrome.ctb"})).unwrap(); + let c13 = got["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Color_13").unwrap(); + assert_eq!(c13["lineweight"], 30); + // Removing a style of a named table names what went. + s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap(); + s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5"}})).unwrap(); + let r = s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5"})).unwrap(); + assert_eq!((r["removedStyle"].as_str(), r["styles"].as_u64()), (Some("Pen 5"), Some(1)), "{r}"); + assert!(r.get("style").is_none(), "{r}"); +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index b7eee854e9..6f84af1649 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -226,6 +226,22 @@ fn find_text_reads_texts_and_render_shows_one_area() { assert_eq!((w, h), (1600, 800)); } +/// Guards #3011: `find_text` filters by `query` as it does by `contains`, instead of ignoring it +/// and returning every text. +#[test] +fn find_text_filters_by_query() { + let mut s = Server::new(Box::new(Headless::default())); + call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"})); + tool(&mut s, "execute", json!({"command": "text", "params": {"at": [1, 1], "height": 0.15, "text": "RECAMARA 1"}})); + tool(&mut s, "execute", json!({"command": "text", "params": {"at": [50, 1], "height": 0.15, "text": "COCINA"}})); + assert_eq!(tool(&mut s, "find_text", json!({}))["count"], 2); + let r = tool(&mut s, "find_text", json!({"query": "cocina"})); + assert_eq!((r["count"].as_u64(), r["texts"][0]["text"].as_str()), (Some(1), Some("COCINA")), "{r}"); + assert_eq!(tool(&mut s, "find_text", json!({"query": "nada"}))["count"], 0); + // `contains` still works and wins when both are given. + assert_eq!(tool(&mut s, "find_text", json!({"contains": "recamara", "query": "cocina"}))["texts"][0]["text"], "RECAMARA 1"); +} + /// Guards a lazy Remote bridge: it serves tools without the app, reports how to start it /// (`--control`), and reaches the app once that app starts listening on the port. #[test] diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 8518a9affa..b71c79d4fb 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -28,8 +28,8 @@ pub fn tool_definitions(has_ui: bool) -> Value { "background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""}, "plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"}, "path": {"type": "string"}}}}), - json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.", - "inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"}, + json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case; `query` is the same filter), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.", + "inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "query": {"type": "string"}, "layer": {"type": "string"}, "window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2}, "limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}), json!({"name": "new_drawing", "description": "Create a new drawing (imperial by default, or metric).", diff --git a/docs/mcp.md b/docs/mcp.md index 504ca2c15d..bc5cdfe36f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -48,7 +48,7 @@ Example client configuration (Claude Code / Claude Desktop): | `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. | | `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). | | `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. | -| `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). | +| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). | | `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. | | `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. | From 39a2e4da07e587bf626aa913e944fcee6b7de6e3 Mon Sep 17 00:00:00 2001 From: cdwilson127 Date: Wed, 11 Nov 2026 16:21:26 +1000 Subject: [PATCH 2/4] stylesmanager set replies with only what changed (#3011) The reply carried the table summary (kind, style count, inDrawing, builtin) next to the edit. #3011 asks for only the changed style, so `set` now replies with the table's name and what the call changed: the edited `style`, the `removedStyle` name and the `description`, each only when given. The test checks that nothing else is in the reply. --- crates/engine/src/cmd/layout/plotstyle.rs | 22 +++++++++++----------- crates/engine/tests/it/plot_styles.rs | 18 ++++++++++++------ docs/plot-styles.md | 3 ++- 3 files changed, 25 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index 8353e68c77..260f7e087a 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -285,22 +285,22 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { } } let t = t.sanitized(); - // Just what changed, not the whole table (a colour-dependent one has 255 styles): the - // table summary as `new` and `load` reply, the edited style, the removed style's name. - let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n)).and_then(|x| serde_json::to_value(x).ok())); - let removed = str_param(p, "removeStyle").map(str::trim); - let name = t.name.clone(); - store(s.doc_mut()?, t); - let d = s.doc()?; - let mut out = table_summary(d, &find_table(cmd, d, &name)?); + // Only what changed, not the table (a colour-dependent one has 255 styles): the table's + // name, the description if given, the edited style and the removed style's name. + let mut out = json!({ "name": t.name }); if let Some(o) = out.as_object_mut() { - if let Some(e) = edited { + if str_param(p, "description").is_some() { + o.insert("description".into(), json!(t.description)); + } + let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n))); + if let Some(e) = edited.and_then(|x| serde_json::to_value(x).ok()) { o.insert("style".into(), e); } - if let Some(r) = removed { - o.insert("removedStyle".into(), json!(r)); + if let Some(r) = str_param(p, "removeStyle") { + o.insert("removedStyle".into(), json!(r.trim())); } } + store(s.doc_mut()?, t); Ok(out) } "delete" => { diff --git a/crates/engine/tests/it/plot_styles.rs b/crates/engine/tests/it/plot_styles.rs index 6b9e27cbc3..dd94157966 100644 --- a/crates/engine/tests/it/plot_styles.rs +++ b/crates/engine/tests/it/plot_styles.rs @@ -62,8 +62,8 @@ fn stylesmanager_creates_edits_saves_and_loads_tables() { &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5", "color": "#00ff00", "screening": 40, "lineweight": 0.35, "linetype": "HIDDEN", "end": "round"}}), ) .unwrap(); - // `set` replies with the table summary and the edited style, not the whole table. - assert_eq!(r["styles"], 2); + // `set` replies with the table's name and the edited style, not the table. + assert_eq!(r["name"], "office.stb"); let pen = r["style"].clone(); assert_eq!(pen["name"], "Pen 5"); assert_eq!( @@ -141,8 +141,11 @@ fn stylesmanager_set_replies_with_the_change_not_the_whole_table() { let mut s = Session::new(); let set = json!({"action": "set", "name": "monochrome.ctb", "style": {"name": "Color_13", "lineweight": 0.3}}); let r = s.execute("stylesmanager", &set).unwrap(); - assert_eq!((r["name"].as_str(), r["styles"].as_u64()), (Some("monochrome.ctb"), Some(255)), "{r}"); + assert_eq!(r["name"], "monochrome.ctb", "{r}"); assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some("Color_13"), Some(30)), "{r}"); + // Only the change: no table summary, no other style. + let keys: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect(); + assert_eq!(keys, ["name", "style"], "{r}"); assert!(r.to_string().len() < 1000, "the reply is short, not the 255-style table: {} bytes", r.to_string().len()); // The edit is in the drawing. let got = s.execute("stylesmanager", &json!({"action": "get", "name": "monochrome.ctb"})).unwrap(); @@ -151,7 +154,10 @@ fn stylesmanager_set_replies_with_the_change_not_the_whole_table() { // Removing a style of a named table names what went. s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap(); s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5"}})).unwrap(); - let r = s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5"})).unwrap(); - assert_eq!((r["removedStyle"].as_str(), r["styles"].as_u64()), (Some("Pen 5"), Some(1)), "{r}"); - assert!(r.get("style").is_none(), "{r}"); + let r = + s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5", "description": "Office pens"})).unwrap(); + assert_eq!((r["removedStyle"].as_str(), r["description"].as_str()), (Some("Pen 5"), Some("Office pens")), "{r}"); + assert!(r.get("style").is_none() && r.get("styles").is_none(), "{r}"); + let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap(); + assert_eq!(got["styles"].as_array().map(Vec::len), Some(1), "{got}"); } diff --git a/docs/plot-styles.md b/docs/plot-styles.md index 55fc300aba..fab29c99ac 100644 --- a/docs/plot-styles.md +++ b/docs/plot-styles.md @@ -81,7 +81,8 @@ prints as `Normal`. A colour-dependent table ignores the property. style and the named styles. - `layer.set {name, plotStyle}` sets a layer's plot style. - `stylesmanager {action, …}` manages the tables: `list`, `get`, `new` (`kind`, `from`), `set` - (`style: {name, …fields}`, `removeStyle`, `description`), `delete`, `load` (`path` or `text`) + (`style: {name, …fields}`, `removeStyle`, `description`; it replies with the table's name and + only what changed), `delete`, `load` (`path` or `text`) and `save` (`path`, or returns `text`). Typed or chosen from **File ▸ Plot Styles...**, it opens the Plot Style Manager dialog. From b4c76bb7968e2d77b23fb557bb1a92f461ff4d19 Mon Sep 17 00:00:00 2001 From: cdwilson127 Date: Wed, 11 Nov 2026 22:13:53 +1300 Subject: [PATCH 3/4] stylesmanager set: a long style name finds and replies with the stored style (#3011) A style name over 255 characters was looked up and reported by its full name, but stored cut to 255. The reply then left out `style`, and setting the same long name again added a second style that `sanitized` dropped, so the edit was lost. The name is now cut to its stored form first. --- crates/engine/src/cmd/layout/plotstyle.rs | 5 ++++- crates/engine/tests/it/plot_styles.rs | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index 260f7e087a..44223634a8 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -268,6 +268,9 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { if let Some(v) = p.get("style") { let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?; + // The name as it is stored (at most 255 characters, as `sanitized` cuts it), so a + // long name finds the style it was stored as and the reply finds the edited style. + let sname: &str = &sname.chars().take(255).collect::(); changed = Some(sname.to_string()); let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) { Some(i) => i, @@ -275,7 +278,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { if t.styles.len() >= cadcraft_doc::MAX_NAMED_STYLES { return Err(bad(cmd, "the table has too many styles")); } - t.styles.push(PlotStyle::object(&sname.chars().take(255).collect::())); + t.styles.push(PlotStyle::object(sname)); t.styles.len() - 1 } None => return Err(bad(cmd, format!("`{name}` has no style `{sname}` (colour-dependent styles are Color_1 to Color_255)"))), diff --git a/crates/engine/tests/it/plot_styles.rs b/crates/engine/tests/it/plot_styles.rs index dd94157966..c13e7e9d56 100644 --- a/crates/engine/tests/it/plot_styles.rs +++ b/crates/engine/tests/it/plot_styles.rs @@ -161,3 +161,22 @@ fn stylesmanager_set_replies_with_the_change_not_the_whole_table() { let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap(); assert_eq!(got["styles"].as_array().map(Vec::len), Some(1), "{got}"); } + +/// A style name over 255 characters is stored cut to 255: the reply names the stored style, and +/// setting the same long name again edits that style instead of adding one. +#[test] +fn stylesmanager_set_with_a_long_style_name_replies_with_the_stored_style() { + let mut s = Session::new(); + s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap(); + let long = "P".repeat(300); + let stored = "P".repeat(255); + let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}}); + let r = s.execute("stylesmanager", &set(0.3)).unwrap(); + assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}"); + let r = s.execute("stylesmanager", &set(0.5)).unwrap(); + assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}"); + let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap(); + let styles = got["styles"].as_array().unwrap(); + assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}"); + assert_eq!(styles[1]["lineweight"], 50, "{got}"); +} From 2423f45e49424eed1d02ac4d291a134456721b00 Mon Sep 17 00:00:00 2001 From: cdwilson127 Date: Sat, 14 Nov 2026 22:48:06 +1300 Subject: [PATCH 4/4] stylesmanager set: a long style name cut at a space finds its stored style (#3011) `sanitized` trims a style name, then cuts it to 255 characters. A name cut at a space was looked up with that trailing space, but the next `sanitized` trims it: the reply left out `style`, and setting the same name again added a second style that `sanitized` dropped, so the edit was lost. The cut name is now trimmed at the end too, as it is stored. --- crates/engine/src/cmd/layout/plotstyle.rs | 8 +++++--- crates/engine/tests/it/plot_styles.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout/plotstyle.rs b/crates/engine/src/cmd/layout/plotstyle.rs index 44223634a8..0a2f95b264 100644 --- a/crates/engine/src/cmd/layout/plotstyle.rs +++ b/crates/engine/src/cmd/layout/plotstyle.rs @@ -268,9 +268,11 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result { if let Some(v) = p.get("style") { let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()); let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?; - // The name as it is stored (at most 255 characters, as `sanitized` cuts it), so a - // long name finds the style it was stored as and the reply finds the edited style. - let sname: &str = &sname.chars().take(255).collect::(); + // The name as it is stored (at most 255 characters, as `sanitized` cuts it, and + // without a space the cut leaves at the end, which `sanitized` trims), so a long + // name finds the style it was stored as and the reply finds the edited style. + let cut: String = sname.chars().take(255).collect(); + let sname = cut.trim_end(); changed = Some(sname.to_string()); let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) { Some(i) => i, diff --git a/crates/engine/tests/it/plot_styles.rs b/crates/engine/tests/it/plot_styles.rs index c13e7e9d56..b1e160ece9 100644 --- a/crates/engine/tests/it/plot_styles.rs +++ b/crates/engine/tests/it/plot_styles.rs @@ -180,3 +180,22 @@ fn stylesmanager_set_with_a_long_style_name_replies_with_the_stored_style() { assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}"); assert_eq!(styles[1]["lineweight"], 50, "{got}"); } + +/// A long name whose 255th character is a space is stored without it (`sanitized` trims the cut +/// name), so the reply still has the style and setting the same name again edits it. +#[test] +fn stylesmanager_set_with_a_long_name_cut_at_a_space_edits_one_style() { + let mut s = Session::new(); + s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap(); + let long = format!("{} tail", "P".repeat(254)); + let stored = "P".repeat(254); + let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}}); + let r = s.execute("stylesmanager", &set(0.3)).unwrap(); + assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}"); + let r = s.execute("stylesmanager", &set(0.5)).unwrap(); + assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}"); + let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap(); + let styles = got["styles"].as_array().unwrap(); + assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}"); + assert_eq!(styles[1]["lineweight"], 50, "{got}"); +}