From a0e5e6eb14d417854b155bc2aa571408f43c44d9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 19:49:52 +0200 Subject: [PATCH] Count tool: deleting an earlier count group keeps the active group (#5653) count.deleteGroup only clamped the active index to the new length, so removing a group before the active one silently made the next group active and later count.add calls landed there. Shift the index down when the removed group precedes it; deleting the active last group still selects the new last group. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/analysis_cmds.rs | 4 +++- crates/engine/src/analysis_cmds/tests.rs | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/analysis_cmds.rs b/crates/engine/src/analysis_cmds.rs index 6ad25951db..7cfd07e48e 100644 --- a/crates/engine/src/analysis_cmds.rs +++ b/crates/engine/src/analysis_cmds.rs @@ -856,7 +856,9 @@ fn count_delete_group(s: &mut Session, p: &Value) -> Result { s.edit("Delete Count Group", |d, _| { d.measurement.count_groups.remove(g); let n = d.measurement.count_groups.len(); - d.measurement.active_count_group = d.measurement.active_count_group.min(n.saturating_sub(1)); + // Removing a group before the active one shifts it down a slot. + let a = d.measurement.active_count_group; + d.measurement.active_count_group = (if g < a { a - 1 } else { a }).min(n.saturating_sub(1)); Ok(()) })?; Ok(count_json(doc(s)?.as_ref())) diff --git a/crates/engine/src/analysis_cmds/tests.rs b/crates/engine/src/analysis_cmds/tests.rs index 124f9abf1e..6c1c6b6242 100644 --- a/crates/engine/src/analysis_cmds/tests.rs +++ b/crates/engine/src/analysis_cmds/tests.rs @@ -291,6 +291,27 @@ fn count_groups_markers_and_undo() { assert!(s.execute("count.add", json!({"x": 1})).is_err()); } +#[test] +fn deleting_an_earlier_count_group_keeps_the_active_group() { + let mut s = session(100, 100, 8); + s.execute("count.add", json!({"x": 10, "y": 10})).unwrap(); + for _ in 0..3 { + s.execute("count.newGroup", json!({})).unwrap(); + } + s.execute("count.setGroup", json!({"group": 2})).unwrap(); + let r = s.execute("count.deleteGroup", json!({"group": 0})).unwrap(); + assert_eq!(r["activeGroup"], 1); + assert_eq!(r["groups"][1]["name"], "Count Group 3"); + // A later group leaves the active index alone. + let r = s.execute("count.deleteGroup", json!({"group": 2})).unwrap(); + assert_eq!(r["activeGroup"], 1); + assert_eq!(r["groups"][1]["name"], "Count Group 3"); + // Deleting the active last group selects the new last group. + let r = s.execute("count.deleteGroup", json!({})).unwrap(); + assert_eq!(r["activeGroup"], 0); + assert_eq!(r["groups"][0]["name"], "Count Group 2"); +} + #[test] fn log_delete_and_csv_export() { let mut s = session(10, 10, 8);