From 7f56589f5a146676f971cd78ae7357a98cb4d6c0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 22:55:39 +0100 Subject: [PATCH 1/7] Add Anchor: reach a segment within 5 points The reference application adds an anchor when a click is up to 5 px from a segment at 100 % and adds none at 6 px. The overlay's segments hit within a line's 4 points, so a click 4.5 or 5 points away added nothing under Add Anchor. craft-behavior's polyline hit shape gets its own reach (`HitShape::polyline_within`; `polyline` keeps `LINE_REACH`), and the overlay gives Add Anchor's segments a 5-point reach. Delete Anchor, Direct Selection and the other tools keep a line's reach. Co-Authored-By: Claude Opus 5.5 --- crates/behavior/src/hit.rs | 38 +++++++++++++++---- crates/draw/src/ui/pen/bezier/mod.rs | 20 +++++++--- crates/draw/tests/it/bezier.rs | 57 ++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 12 deletions(-) diff --git a/crates/behavior/src/hit.rs b/crates/behavior/src/hit.rs index 1a77ccf26..0ca496cdd 100644 --- a/crates/behavior/src/hit.rs +++ b/crates/behavior/src/hit.rs @@ -30,13 +30,15 @@ pub enum HitShape { /// The other end. b: Pos2, }, - /// A chain of segments, hit within [`LINE_REACH`]. + /// A chain of segments, hit within `reach` ([`LINE_REACH`] unless [`HitShape::polyline_within`] says otherwise). #[non_exhaustive] Polyline { /// The corners in order. points: Vec, /// Whether the last corner joins the first. closed: bool, + /// How far from the chain a point still hits it, in points. + reach: f32, }, /// A filled polygon. Polygon(Vec), @@ -62,9 +64,16 @@ impl HitShape { HitShape::Segment { a, b } } - /// A chain of segments, closed when `closed`. + /// A chain of segments, closed when `closed`, hit within [`LINE_REACH`]. pub fn polyline(points: Vec, closed: bool) -> Self { - HitShape::Polyline { points, closed } + HitShape::Polyline { points, closed, reach: LINE_REACH } + } + + /// A chain of segments, closed when `closed`, hit within `reach` points: a tool whose measured reach differs from + /// a line's. A negative or non-finite `reach` is [`LINE_REACH`]. + pub fn polyline_within(points: Vec, closed: bool, reach: f32) -> Self { + let reach = if reach.is_finite() && reach >= 0.0 { reach } else { LINE_REACH }; + HitShape::Polyline { points, closed, reach } } /// The part of `within` outside `polygon`. @@ -95,7 +104,8 @@ impl HitShape { } HitShape::Circle { center, radius } => center.distance(point) <= radius.max(across / 2.0), HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= reach, - HitShape::Polyline { points, closed } => { + HitShape::Polyline { points, closed, reach: own } => { + let reach = own.max(across / 2.0); let closing = closed.then(|| points.first().zip(points.last())).flatten(); points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= reach) || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= reach) @@ -116,10 +126,10 @@ impl HitShape { HitShape::Rect(rect) => rect.contains(point), HitShape::Circle { center, radius } => center.distance(point) <= *radius, HitShape::Segment { a, b } => segment_distance(point, *a, *b) <= LINE_REACH, - HitShape::Polyline { points, closed } => { + HitShape::Polyline { points, closed, reach } => { let closing = closed.then(|| points.first().zip(points.last())).flatten(); - points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= LINE_REACH) - || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= LINE_REACH) + points.windows(2).any(|pair| segment_distance(point, pair[0], pair[1]) <= *reach) + || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= *reach) } HitShape::Polygon(points) => inside_polygon(point, points), HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon), @@ -330,4 +340,18 @@ mod tests { let tie = [shape(big(), Sense::CLICK, 1, 0, HitLevel::Body, 0), shape(big(), Sense::CLICK, 2, 0, HitLevel::Body, 0)]; assert_eq!(owner(&tie), Some(2)); } + + #[test] + fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() { + let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)]; + let line = HitShape::polyline(points.clone(), false); + assert!(line.hit(pos2(50.0, LINE_REACH)) && !line.hit(pos2(50.0, LINE_REACH + 0.5))); + let wide = HitShape::polyline_within(points.clone(), false, 5.0); + assert!(wide.hit(pos2(50.0, 5.0)) && wide.hit(pos2(50.0, -5.0)) && !wide.hit(pos2(50.0, 5.5))); + let hits = |shape: HitShape, y: f32| Shape::new(shape, Sense::CLICK, 0_u8, None, HitPriority::BODY, 0).min_across(8.0).hits(pos2(50.0, y)); + assert!(hits(wide.clone(), 5.0) && !hits(wide, 5.5), "a target size under twice the reach keeps the reach"); + for bad in [f32::NAN, f32::INFINITY, -1.0] { + assert_eq!(HitShape::polyline_within(points.clone(), false, bad), line); + } + } } diff --git a/crates/draw/src/ui/pen/bezier/mod.rs b/crates/draw/src/ui/pen/bezier/mod.rs index 20e1d040a..0f58a91b5 100644 --- a/crates/draw/src/ui/pen/bezier/mod.rs +++ b/crates/draw/src/ui/pen/bezier/mod.rs @@ -47,6 +47,11 @@ use super::{PathOptionsSettings, PathTool}; /// Insert on a picked anchor adds one halfway along the segment leaving it. const INSERT: Chord = Chord::plain(Key::Insert); +/// How far from a segment, in screen points, an Add Anchor press or hover still takes it: the reference application +/// adds an anchor 5 px from a segment at 100 % and none at 6 px. The other tools keep a line's reach +/// ([`LINE_REACH`](craft_behavior::hit::LINE_REACH)). +const ADD_ANCHOR_REACH: f32 = 5.0; + /// Above this many anchors in the paths shown, the overlay draws outlines only and declares no part (no anchor in /// the AccessKit tree either) (VectorCraft's `OVERLAY_MAX_ANCHORS`). pub const MAX_ANCHORS: usize = 100_000; @@ -66,10 +71,10 @@ pub enum BezierTool { Convert, /// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools). Anchors, - /// Add Anchor Point: a press on a segment inserts an anchor at the hit's `t` ([`PathEdit::InsertAnchor`]); a drag - /// moves the new anchor, which is selected; ⌥ makes it Delete Anchor Point. Hover: the segment mark with the - /// anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor the arrow; the crosshair under the - /// canvas's precise cursor ([`CanvasSpace::precise`]). + /// Add Anchor Point: a press on a segment, within 5 screen points of it, inserts an anchor at the hit's `t` + /// ([`PathEdit::InsertAnchor`]); a drag moves the new anchor, which is selected; ⌥ makes it Delete Anchor Point. + /// Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor the + /// arrow; the crosshair under the canvas's precise cursor ([`CanvasSpace::precise`]). AddAnchor, /// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it /// Add Anchor Point, except that a ⌥ click on an anchor selects its whole subpath. Hover: the anchor mark. @@ -504,13 +509,18 @@ impl<'a> BezierOverlay<'a> { let start = if ends && i == 0 { reach } else { 0.0 }; let end = if ends && i + 1 == sub.segment_count() { reach } else { 0.0 }; let Some(points) = trim_polyline(points, start, end) else { continue }; + let shape = if self.tool == BezierTool::AddAnchor { + HitShape::polyline_within(points, false, ADD_ANCHOR_REACH) + } else { + HitShape::polyline(points, false) + }; items.push(Item { kind: Kind::Segment, path: at, key: path.key, knot: KnotRef::new(s, i), at: corners[0], - shape: HitShape::polyline(points, false), + shape, interior: true, straight: sub.is_straight(i), shown: true, diff --git a/crates/draw/tests/it/bezier.rs b/crates/draw/tests/it/bezier.rs index 1cd1cb17a..ed91f4df5 100644 --- a/crates/draw/tests/it/bezier.rs +++ b/crates/draw/tests/it/bezier.rs @@ -744,6 +744,63 @@ fn add_anchor_shows_the_pen_with_plus_over_a_segment_and_the_arrow_over_an_ancho } } +// Add Anchor reaches a segment within 5 screen points, as the reference application does (PhotoCraft #12732): a click +// 2 to 5 points above or below a straight segment adds an anchor and shows the pen with "+", one 5.5 or 6 points away +// adds nothing; Delete Anchor and Direct Selection keep a line's reach. +#[trial] +fn add_anchor_reaches_a_segment_within_5_points() { + use craft_behavior::{Cursor, CursorBadge, PaintedCursor}; + let segment = p(110.0, 60.0); + let at_tool = |tool: BezierTool| { + let mut h = two_paths(); + h.update(|st| st.tool = tool); + h + }; + let click = |h: &mut Harness, at: Pos2| { + h.press_at(at); + h.release_at(at); + }; + let pen_plus = |h: &Harness| { + matches!( + craft_ui::runtime::cursor::current(h.fixture.ctx()), + Some(Cursor::Painted(PaintedCursor::Tool { badge: Some(CursorBadge::Add), .. })) + ) + }; + for off in [2.0_f32, 3.0, 4.5, 5.0, -2.0, -5.0] { + let mut h = at_tool(BezierTool::AddAnchor); + let at = h.screen(segment) + vec2(0.0, off); + h.move_to(at); + h.fixture.frame(Vec::new()); + assert!(pen_plus(&h), "{off}: the pen with + shows where a click adds"); + click(&mut h, at); + let st = h.state.borrow(); + assert!(matches!(st.changes.last(), Some(PathEdit::InsertAnchor { path: 1, segment, .. }) if *segment == kr(0)), "{off}: {:?}", st.changes); + assert_eq!(st.paths[0].subpaths[0].knots.len(), 5, "{off}"); + } + for off in [5.5_f32, 6.0, -6.0] { + let mut h = at_tool(BezierTool::AddAnchor); + let at = h.screen(segment) + vec2(0.0, off); + h.move_to(at); + h.fixture.frame(Vec::new()); + assert!(!pen_plus(&h), "{off}: no + past the reach"); + click(&mut h, at); + let st = h.state.borrow(); + assert!(st.changes.is_empty() && st.seen.is_empty(), "{off}: {:?} {:?}", st.changes, st.seen); + assert_eq!(st.paths, [path_a(), path_b()], "{off}"); + } + // The other tools keep a line's reach: 4.5 points from the segment misses it, 3 points hits it. + for tool in [BezierTool::DeleteAnchor, BezierTool::Direct] { + let mut h = at_tool(tool); + let near = h.screen(segment) + vec2(0.0, 3.0); + h.drag(near, vec2(0.0, FAR)); + assert!(matches!(h.last_change(), Some(PathEdit::BendSegment { path: 1, .. })), "{tool:?}: {:?}", h.last_change()); + let mut h = at_tool(tool); + let past = h.screen(segment) + vec2(0.0, 4.5); + h.drag(past, vec2(0.0, FAR)); + assert!(!matches!(h.last_change(), Some(PathEdit::BendSegment { .. })), "{tool:?}: {:?}", h.last_change()); + } +} + // The anchor tools' canvas tool: a press off the paths begins nothing (it never starts a path), and off the paths the // cursor says what a click does: the arrow for Add Anchor (the pen with "-" under ⌥, where a click deletes), the pen // with "-" for Delete Anchor, the Convert Point icon, the arrow for Direct Selection and under ⌘, the crosshair when From d06fd33dfb967e28fc69e8692e41bf804c4658cb Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:39:51 +0000 Subject: [PATCH 2/7] Add count-trial counters for settling, text layout and measure asks, and an idle-frame trial --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 19 ++- crates/ui-contract/src/runtime/measure.rs | 116 ++++++++++++++++++ crates/ui-contract/src/testing/mod.rs | 5 +- crates/ui-widgets/tests/it/body/settle.rs | 72 +++++++---- 7 files changed, 190 insertions(+), 25 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6293bebde..856259c7a 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 0170bb71d..e75201bd6 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size))); diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 113581b1b..1d64bf0df 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 8cefd9fb5..7850311c1 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -240,7 +240,7 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { /// pass gets the same answer, so a measuring run and the real run lay out the same children. pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision { let targets = crate::runtime::focus::targets(ctx); - with(ctx, |store, pass_nr, frame| { + let decision = with(ctx, |store, pass_nr, frame| { let entry = store.touch(Some(view.owner), id, frame); let kind = usize::from(!sizing); // A child the other kind of run showed last takes that run's extent. @@ -255,7 +255,11 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - } }; if skip { Decision::Skip(size) } else { Decision::Run } - }) + }); + if matches!(decision, Decision::Skip(_)) { + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); + } + decision } /// Records what a run that showed the child `id` found: its extent in a run of this kind and, from a real run, what @@ -298,6 +302,17 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { + use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; + // The 8 bytes of a keyed call's content version are the key fed in. + if content.is_some() { + count_memo_key_bytes(ctx, 8); + } + let size = decide_settled(ctx, owner, id, sizing, place, content); + count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); + size +} + +fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index c281c04a5..5bed8a5e6 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -305,3 +305,119 @@ pub(crate) fn count_least(ctx: &Context, id: Id) { pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| log.runs.clone()) } + +/// What a settling child's decision was. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Settle { + /// The child ran. + Ran, + /// The child's last run was replayed in place of running. + Replayed, + /// The child is out of view and took its last extent without running. + OutOfView, +} + +/// The settled-test decisions of one pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct SettleLog { + pass: u64, + decisions: Vec<(Id, Settle)>, +} + +/// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and +/// `lazy::decide` (out of view); a rename of that decision point moves both calls. +pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { + #[cfg(feature = "testing")] + { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); + } + #[cfg(not(feature = "testing"))] + let _ = (ctx, id, what); +} + +/// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. +#[cfg(feature = "testing")] +pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) +} + +/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct PassTotals { + pass: u64, + key_bytes: usize, + text_layouts: u32, + asks: Vec<(&'static str, u32)>, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = PassTotals { pass, ..PassTotals::default() }; + } + f(log) + }) +} + +#[cfg(feature = "testing")] +fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) +} + +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.key_bytes += bytes); + #[cfg(not(feature = "testing"))] + let _ = (ctx, bytes); +} + +/// The bytes fed into memo keys in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { + last_totals(ctx, |log| log.key_bytes, 0) +} + +/// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +pub(crate) fn count_text_layout(ctx: &Context) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.text_layouts += 1); + #[cfg(not(feature = "testing"))] + let _ = ctx; +} + +/// The text layouts handed to egui in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_text_layouts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.text_layouts, 0) +} + +/// Counts a measure call of a leaf component of the type `name` in this pass. +pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { + #[cfg(feature = "testing")] + totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { + Some((_, count)) => *count += 1, + None => log.asks.push((name, 1)), + }); + #[cfg(not(feature = "testing"))] + let _ = (ctx, name); +} + +/// The leaf types that were asked to measure in the last pass, and how many times each. +#[cfg(feature = "testing")] +pub fn last_pass_measure_asks(ctx: &Context) -> Vec<(&'static str, u32)> { + last_totals(ctx, |log| log.asks.clone(), Vec::new()) +} diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 90ed467df..9dcb90e6a 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -41,8 +41,9 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ - active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, - last_pass_runs, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + Settle, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, + last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_runs, last_pass_settles, + last_pass_text_layouts, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index f7dae2c36..317b8d902 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -13,7 +13,7 @@ use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Comm use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; -use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial}; +use craft_ui::testing::{Fixture, Frames, Settle, last_pass_measuring_runs, last_pass_runs, last_pass_settles, last_pass_text_layouts, trial}; use egui::{Id, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -36,6 +36,8 @@ struct Scene { versions: [Cell>; 2], repaints: Cell, app_repaints: Cell, + /// Whether the scene shows only what is outside the settling children. + bare: Cell, runs: [Cell; 2], buttons: [Cell<(Id, Rect)>; 2], seen: Seen, @@ -51,6 +53,7 @@ impl Scene { versions: Default::default(), repaints: Cell::new(false), app_repaints: Cell::new(false), + bare: Cell::new(false), runs: Default::default(), buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))], seen: Seen::default(), @@ -73,28 +76,30 @@ impl Scene { if self.editor_first { self.editor(ui); } - in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { - self.child("reader", 0).show(ui, |ui| { - self.runs[0].set(self.runs[0].get() + 1); - let response = Button::new("Alpha").show(ui).response; - self.buttons[0].set((response.id, response.rect)); - Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); - }); - self.child("other", 1).show(ui, |ui| { - self.runs[1].set(self.runs[1].get() + 1); - if self.repaints.get() { - frame::request_repaint(ui.ctx()); - } - // In a body, whose measure a run that is not settled takes from what its last run kept. - Stack::new().show(ui, |ui, _| { - let response = Button::new("Beta").show(ui).response; - self.buttons[1].set((response.id, response.rect)); + if !self.bare.get() { + in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { + self.child("reader", 0).show(ui, |ui| { + self.runs[0].set(self.runs[0].get() + 1); + let response = Button::new("Alpha").show(ui).response; + self.buttons[0].set((response.id, response.rect)); + Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); + }); + self.child("other", 1).show(ui, |ui| { + self.runs[1].set(self.runs[1].get() + 1); + if self.repaints.get() { + frame::request_repaint(ui.ctx()); + } + // In a body, whose measure a run that is not settled takes from what its last run kept. + Stack::new().show(ui, |ui, _| { + let response = Button::new("Beta").show(ui).response; + self.buttons[1].set((response.id, response.rect)); + }); + if self.spinner { + Spinner::new().show(ui); + } }); - if self.spinner { - Spinner::new().show(ui); - } }); - }); + } if !self.editor_first { self.editor(ui); } @@ -146,6 +151,31 @@ fn a_settled_child_does_not_run_and_still_paints() { } } +/// After two warm-up frames, an idle frame with no input runs nothing that settles: every keyed child replays, the +/// components that run are those outside every settling child, the frame takes one pass and lays out no text. +#[trial] +fn an_idle_frame_runs_nothing_that_settles() { + let scene = Scene::new(false, false); + scene.versions.iter().for_each(|version| version.set(Some(1))); + let mut frames = Frames::new(); + scene.settle(&mut frames); + let reference = Scene::new(false, false); + reference.bare.set(true); + let mut bare = Frames::new(); + reference.settle(&mut bare); + let outside = { + reference.frame(&mut bare, vec![]); + last_pass_runs(&bare.ctx).iter().map(|(_, runs)| runs).sum::() + }; + let passes = frames.frame(vec![], |ui| scene.show(ui)); + let ran = last_pass_settles(&frames.ctx).into_iter().filter(|(_, what)| *what == Settle::Ran).count(); + let runs = last_pass_runs(&frames.ctx); + assert_eq!(ran, 0, "an idle frame ran keyed children: {:?}", last_pass_settles(&frames.ctx)); + assert_eq!(runs.iter().map(|(_, runs)| runs).sum::(), outside, "components ran inside settling children: {runs:?}"); + assert_eq!(passes, 1, "an idle frame takes one pass"); + assert_eq!(last_pass_text_layouts(&frames.ctx), 0, "an idle frame laid out text"); +} + /// The pointer over a settled child runs it, and only it, in the frame it arrives, from the measures its last run /// kept; leaving, the child runs until its hover has faded out, then settles again. #[trial] From ce3513f84a3a8fd2403298d5adfc0c0920f5d999 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:41:32 +0000 Subject: [PATCH 3/7] Gate the counters on the testing feature --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 23 ++++++------ crates/ui-contract/src/runtime/measure.rs | 35 +++++++------------ 5 files changed, 29 insertions(+), 32 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 856259c7a..6ccec0dbf 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + #[cfg(feature = "testing")] crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index e75201bd6..237e116be 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 1d64bf0df..d07364659 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 7850311c1..b6fd3756c 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -256,6 +256,7 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - }; if skip { Decision::Skip(size) } else { Decision::Run } }); + #[cfg(feature = "testing")] if matches!(decision, Decision::Skip(_)) { crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); } @@ -302,17 +303,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { - use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; - // The 8 bytes of a keyed call's content version are the key fed in. + // Keyed calls feed their 8-byte content version into the key. + #[cfg(feature = "testing")] if content.is_some() { - count_memo_key_bytes(ctx, 8); + crate::runtime::measure::count_memo_key_bytes(ctx, 8); } - let size = decide_settled(ctx, owner, id, sizing, place, content); - count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); - size -} - -fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); @@ -355,15 +350,23 @@ fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: settled.map(|settled| (entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(settled.rect.size()), settled)) }); // The pointer over it, or a press that started on it, is read outside the store. - let (size, settled) = settled?; + let Some((size, settled)) = settled else { + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); + return None; + }; if engaged(ctx, &settled) { with(ctx, |store, pass_nr, _| { if let Some(entry) = store.entries.get_mut(&id) { entry.replays = Some((pass_nr, false)); } }); + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); return None; } + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Replayed); Some(size) } diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 5bed8a5e6..85afc682f 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -328,19 +328,15 @@ struct SettleLog { /// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and /// `lazy::decide` (out of view); a rename of that decision point moves both calls. +#[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { - #[cfg(feature = "testing")] - { - let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { - if log.pass != pass { - *log = SettleLog { pass, decisions: Vec::new() }; - } - log.decisions.push((id, what)); - }); - } - #[cfg(not(feature = "testing"))] - let _ = (ctx, id, what); + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); } /// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. @@ -377,12 +373,11 @@ fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } -/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes +/// per call with a content version). +#[cfg(feature = "testing")] pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { - #[cfg(feature = "testing")] totals(ctx, |log| log.key_bytes += bytes); - #[cfg(not(feature = "testing"))] - let _ = (ctx, bytes); } /// The bytes fed into memo keys in the last pass. @@ -392,11 +387,9 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { } /// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_text_layout(ctx: &Context) { - #[cfg(feature = "testing")] totals(ctx, |log| log.text_layouts += 1); - #[cfg(not(feature = "testing"))] - let _ = ctx; } /// The text layouts handed to egui in the last pass. @@ -406,14 +399,12 @@ pub fn last_pass_text_layouts(ctx: &Context) -> u32 { } /// Counts a measure call of a leaf component of the type `name` in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { - #[cfg(feature = "testing")] totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { Some((_, count)) => *count += 1, None => log.asks.push((name, 1)), }); - #[cfg(not(feature = "testing"))] - let _ = (ctx, name); } /// The leaf types that were asked to measure in the last pass, and how many times each. From 972a86af6582034237877a0266097769f62b2baa Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:25:25 +0000 Subject: [PATCH 4/7] Keep the counters in pass-local state; mark Settle non_exhaustive --- crates/ui-contract/src/runtime/measure.rs | 13 +++++++------ crates/ui-contract/src/runtime/pass_state.rs | 4 ++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 85afc682f..912f37b57 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -309,6 +309,7 @@ pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { /// What a settling child's decision was. #[cfg(feature = "testing")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum Settle { /// The child ran. Ran, @@ -321,7 +322,7 @@ pub enum Settle { /// The settled-test decisions of one pass. #[cfg(feature = "testing")] #[derive(Default)] -struct SettleLog { +pub(crate) struct SettleLog { pass: u64, decisions: Vec<(Id, Settle)>, } @@ -331,7 +332,7 @@ struct SettleLog { #[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = SettleLog { pass, decisions: Vec::new() }; } @@ -343,13 +344,13 @@ pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { #[cfg(feature = "testing")] pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) + pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } /// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. #[cfg(feature = "testing")] #[derive(Default)] -struct PassTotals { +pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, @@ -359,7 +360,7 @@ struct PassTotals { #[cfg(feature = "testing")] fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = PassTotals { pass, ..PassTotals::default() }; } @@ -370,7 +371,7 @@ fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { #[cfg(feature = "testing")] fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 9e0fb9443..18f837d8d 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -113,6 +113,10 @@ pass_state! { style_record: crate::testing::style::StyleRecord, #[cfg(feature = "testing")] type_runs: crate::runtime::measure::TypeRuns, + #[cfg(feature = "testing")] + settle_log: crate::runtime::measure::SettleLog, + #[cfg(feature = "testing")] + pass_totals: crate::runtime::measure::PassTotals, } records { focus: crate::runtime::focus::State, From fc8f48ff967337636db58de10e5605f8013a852a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:31:24 +0000 Subject: [PATCH 5/7] Command board: maps for instances, modal roots and shown readers; node facts after the node check; chord texts from the keymap build --- .../ui-contract/src/contract/steps/report.rs | 72 ++++--- .../ui-contract/src/runtime/commands/board.rs | 190 ++++++++++++------ .../ui-contract/src/runtime/commands/mod.rs | 12 +- crates/ui-contract/src/runtime/measure.rs | 15 +- crates/ui-panels/src/rails/flyout.rs | 5 +- crates/ui-shell/tests/it/commands/board.rs | 61 +++++- crates/ui-shell/tests/it/commands/kit.rs | 31 +++ 7 files changed, 279 insertions(+), 107 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 2dd8a846d..7dafc2583 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -6,7 +6,7 @@ use crate::contract::cx::{CxCore, Decls}; use crate::contract::run::{ErasedPass, TypeFacts}; use crate::primitives::FaceRecord; use crate::runtime::access::{self, Access, FaceFacts, Own, Politeness, Role, SetPosition, SubDecl, SubNode, scope}; -use crate::runtime::commands::{self, ResolvedCommand}; +use crate::runtime::commands::ResolvedCommand; use crate::runtime::env::{Label, Message}; use crate::runtime::focus::{self}; use crate::runtime::keys; @@ -33,8 +33,15 @@ pub(crate) struct ReportIn<'a> { } /// The bound command's hint and shortcut text, which describe and key its node. -fn command_facts(command: &ResolvedCommand, platform: craft_keymap::Platform) -> (Option<&str>, Option) { - (command.hint.as_deref(), command.chord.as_ref().map(|chord| chord.display(platform))) +fn command_facts<'a>(ctx: &egui::Context, command: &'a ResolvedCommand) -> (Option<&'a str>, Option<&'a str>) { + let text = command.chord_text.as_deref(); + #[cfg(feature = "testing")] + if text.is_some() { + crate::runtime::measure::count_chord_text(ctx); + } + #[cfg(not(feature = "testing"))] + let _ = ctx; + (command.hint.as_deref(), text) } /// The message of a validity that warns, refuses or errs, and whether it warns. @@ -78,40 +85,10 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> } } *core.value_text.borrow_mut() = value_text; - for node in &mut access.nodes { - if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) { - node.expanded = Some(toggle.open); - } - } let role = access.role.unwrap_or(facts.role); - access.access_key = access.access_key.or(core.resolved.access_key); - if access.grid == access::GridPlace::default() { - access.grid = core.grid; - } debug_assert!(access.role.is_none_or(|alt| facts.alt_roles.contains(&alt)), "`Access::role` picks one of `ALT_ROLES`"); let flags = core.state.flags; let resolved = core.resolved; - let platform = commands::platform(ctx); - let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(command, platform)); - let shortcut = shortcut.as_deref(); - for (_, label) in &mut access.custom_actions { - *label = core.env.resolve(label); - } - let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text)); - let tooltip = tooltip_text.as_ref().map(Label::as_str); - if access.live.is_none() { - access.live = input.live; - } - if access.expanded.is_none() { - access.expanded = input.expanded; - } - if access.position.is_none() { - access.position = input.position; - } - if access.position.is_none() { - access.position = - input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); - } let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { @@ -132,6 +109,35 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> if !input.node { return; } + // Facts that only a node shows are built after the node check. + for node in &mut access.nodes { + if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) { + node.expanded = Some(toggle.open); + } + } + access.access_key = access.access_key.or(core.resolved.access_key); + if access.grid == access::GridPlace::default() { + access.grid = core.grid; + } + let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(ctx, command)); + for (_, label) in &mut access.custom_actions { + *label = core.env.resolve(label); + } + let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text)); + let tooltip = tooltip_text.as_ref().map(Label::as_str); + if access.live.is_none() { + access.live = input.live; + } + if access.expanded.is_none() { + access.expanded = input.expanded; + } + if access.position.is_none() { + access.position = input.position; + } + if access.position.is_none() { + access.position = + input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); + } let inner_of = access::fold::owner_of(ctx, id); let folded = access::fold::take(ctx, id); if access.value.is_none() { diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 0c3d7f8a7..ca350161d 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -32,6 +32,44 @@ enum Declaration { Focused { inactive: bool }, } +/// The registered instances in registration order, which `pick_instance` ranks by, with their positions by id. +#[derive(Default)] +struct Instances { + list: Vec, + at: HashMap, +} + +impl Instances { + fn get(&self, id: Id) -> Option<&Instance> { + self.at.get(&id).map(|at| &self.list[*at]) + } + + fn iter(&self) -> std::slice::Iter<'_, Instance> { + self.list.iter() + } + + /// Registers `instance`, keeping the place of one already registered under the same id. + fn upsert(&mut self, instance: Instance) { + match self.at.get(&instance.id) { + Some(at) => self.list[*at] = instance, + None => { + self.at.insert(instance.id, self.list.len()); + self.list.push(instance); + } + } + } + + /// Keeps the instances `keep` accepts, in their order. + fn retain(&mut self, mut keep: impl FnMut(&Instance) -> bool) { + self.list.retain(|instance| keep(instance)); + self.at = self.list.iter().enumerate().map(|(at, instance)| (instance.id, at)).collect(); + } + + fn contains(&self, id: Id) -> bool { + self.at.contains_key(&id) + } +} + /// A container instance that receives scoped commands. struct Instance { id: Id, @@ -54,6 +92,8 @@ struct KeymapCache { edit_chords: Arc<[(EditCommand, Chord)]>, /// The chords bound to the window's keys, which the input hook takes before any component. window_shortcuts: Arc<[(WindowShortcut, Chord)]>, + /// `BuiltKeymap::shown_text`. + shown_text: Arc>>, } /// A momentary command whose key is down: its release fires the command again. @@ -85,7 +125,7 @@ pub(crate) struct Board { out: Vec, /// The commands instances took since the last `FrameOutput`, in order. delivered: Vec, - instances: Vec, + instances: Instances, /// The focused component of each viewport's last step 12 and the instances around it. chains: HashMap, /// The focused component and its chain before the one in `chains`, per viewport; while the focus is in the menus @@ -98,7 +138,7 @@ pub(crate) struct Board { matcher: Matcher, held: Vec, /// The top modal layer's root container of each viewport that has one. - modal_roots: Vec<(ViewportId, Id)>, + modal_roots: HashMap, /// The states published this pass, and the pass before, by an instance inside the top modal layer. modal_published: HashSet, modal_published_last: HashSet, @@ -129,7 +169,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool { } /// Who read a command's resolution: the vantage `begin` resolves it from again. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Hash)] enum Reader { /// A surface with no component of its own (`resolve_global`): the key focus of the running pass. Global, @@ -142,21 +182,19 @@ enum Reader { InMenu(Id, CommandChain), } -/// What a reader was shown the last time it resolved a command. -struct Shown { - reader: Reader, - resolved: ResolvedCommand, -} - -/// The readers of each state key in each viewport. -type ShownMap = HashMap<(StateKey, ViewportId), Vec>; +/// What each reader was shown the last time it resolved a command, by the viewport and the state key it read. The +/// readers of a key stay in the order they first read it: the gate is app code, and `wake_shown` asks it in that order. +type ShownMap = HashMap>>; /// Keeps `resolved` as what `reader` of `viewport` was shown under `key`, in place of what it was shown before. fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader: Reader, resolved: &ResolvedCommand) { - let readers = shown.entry((key, viewport)).or_default(); - match readers.iter_mut().find(|entry| entry.reader == reader) { - Some(entry) => entry.resolved.clone_from(resolved), - None => readers.push(Shown { reader, resolved: resolved.clone() }), + keep_in(shown.entry(viewport).or_default().entry(key).or_default(), reader, resolved); +} + +fn keep_in(readers: &mut Vec<(Reader, ResolvedCommand)>, reader: Reader, resolved: &ResolvedCommand) { + match readers.iter_mut().find(|(kept, _)| *kept == reader) { + Some((_, kept)) => kept.clone_from(resolved), + None => readers.push((reader, resolved.clone())), } } @@ -238,7 +276,7 @@ impl Board { /// The instance of `scope` a command routed to `at` goes to: `at` when it is an instance of the scope itself (a /// canvas), else the innermost instance in `around`, the chain of the context `at` was shown in. fn instance_around(&self, at: Id, around: &CommandChain, scope: &str) -> Option { - let own = self.instances.iter().any(|i| i.id == at && self.within(i.scope.name(), scope)); + let own = self.instances.get(at).is_some_and(|i| self.within(i.scope.name(), scope)); if own { Some(at) } else { self.innermost(around, scope) } } @@ -262,7 +300,7 @@ impl Board { } fn is_live(&self, ctx: &Context, id: Id) -> bool { - self.instances.iter().any(|i| i.id == id && self.live(ctx, i)) + self.instances.get(id).is_some_and(|i| self.live(ctx, i)) } /// The definition of the command `id`: the linked sets', else the frame's app catalog's. @@ -301,7 +339,7 @@ impl Board { /// is declared inside, after its own. fn scopes_around(&self, chain: &[Id]) -> Vec<&'static str> { let mut scopes: Vec<&'static str> = Vec::new(); - for instance in chain.iter().rev().filter_map(|id| self.instances.iter().find(|i| i.id == *id)) { + for instance in chain.iter().rev().filter_map(|id| self.instances.get(*id)) { let lineage = self.lineage(instance.scope.name()); scopes.push(lineage[0]); let parents: Vec<&'static str> = lineage[1..].iter().copied().filter(|scope| !scopes.contains(scope)).collect(); @@ -318,7 +356,7 @@ impl Board { } fn is_modal_root(&self, id: Id) -> bool { - self.modal_roots.iter().any(|(_, root)| *root == id) + self.modal_roots.values().any(|root| *root == id) } /// Where `command` goes when a source with no component of its own fires it: `None` for an app-scope command, @@ -398,10 +436,12 @@ impl Board { }; let live = app || instance.is_some_and(|id| self.is_live(ctx, id)); let chord = self.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command)); + let chord_text = chord.and_then(|chord| self.keymap.as_ref()?.shown_text.get(&chord).cloned()); let resolved = ResolvedCommand { label: state.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))), icon: def.and_then(|def| def.icon.clone()), chord, + chord_text, enabled: flags.enabled && modal && live && !matches!(declaring, Some(Declaration::Focused { inactive: true })), checked: flags.checked, marked: state.is_some_and(CommandState::is_marked), @@ -464,6 +504,8 @@ struct BuiltKeymap { keymap: Arc, edit_chords: Arc<[(EditCommand, Chord)]>, window_shortcuts: Arc<[(WindowShortcut, Chord)]>, + /// The text of every chord the keymap shows, written once when the keymap is built. + shown_text: Arc>>, } /// The keymap of `defs` on `platform` under `overrides`. @@ -475,6 +517,19 @@ fn keymap_of(defs: Vec, scopes: Scopes, platform: Platform, override keymap } +#[cfg(feature = "testing")] +thread_local! { + static CHORD_TEXT_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many chord texts this thread's keymap builds have written: one per distinct shown chord per build, never one +/// per report. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn chord_text_builds() -> u64 { + CHORD_TEXT_BUILDS.with(std::cell::Cell::get) +} + #[cfg(feature = "testing")] thread_local! { static KEYMAP_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -558,7 +613,17 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.double).map(move |binding| (edit, binding.trigger.chord)) }) .collect(); - BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts } + let mut shown_text = HashMap::new(); + for def in keymap.catalog() { + if let Some(chord) = keymap.shown_chord(&def.command) { + shown_text.entry(chord).or_insert_with(|| { + #[cfg(feature = "testing")] + CHORD_TEXT_BUILDS.with(|builds| builds.set(builds.get() + 1)); + Arc::from(chord.display(platform)) + }); + } + } + BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts, shown_text: Arc::new(shown_text) } } /// The keymap of each shared registry (with or without the stories' sets) on each platform with no overrides. It @@ -596,7 +661,7 @@ pub(crate) fn innermost(ctx: &Context, chain: &CommandChain, scope: &str) -> Opt } /// The platform the keymap and the chords shown are read for. -pub(crate) fn platform(ctx: &Context) -> Platform { +fn platform(ctx: &Context) -> Platform { crate::runtime::windows::os_of(ctx) } @@ -630,9 +695,10 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { }); let mut shadowed = Vec::new(); if stale { - let BuiltKeymap { keymap, edit_chords, window_shortcuts } = + let BuiltKeymap { keymap, edit_chords, window_shortcuts, shown_text } = keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref()); - board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts }); + board.keymap = + Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text }); for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); @@ -699,15 +765,7 @@ fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_in(ctx, scope, id, layer)); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); - with(ctx, |board| match board.instances.iter_mut().find(|i| i.id == id) { - Some(instance) => { - instance.scope = scope; - instance.viewport = viewport; - instance.stamp = stamp; - instance.layer = layer; - } - None => board.instances.push(Instance { id, scope, viewport, stamp, layer }), - }); + with(ctx, |board| board.instances.upsert(Instance { id, scope, viewport, stamp, layer })); } /// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The @@ -731,14 +789,16 @@ pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) { pub(crate) fn set_modal_open(ctx: &Context, open: bool, viewport: ViewportId, root: Option) { with(ctx, |board| { board.here.modal_open = open; - board.modal_roots.retain(|(of, _)| *of != viewport); - board.modal_roots.extend(root.map(|root| (viewport, root))); + match root { + Some(root) => board.modal_roots.insert(viewport, root), + None => board.modal_roots.remove(&viewport), + }; }); } /// The root of the top modal layer of `viewport`, if one is open. pub(crate) fn modal_root(ctx: &Context, viewport: ViewportId) -> Option { - with(ctx, |board| board.modal_roots.iter().find(|(of, _)| *of == viewport).map(|(_, root)| *root)) + with(ctx, |board| board.modal_roots.get(&viewport).copied()) } /// Which instances a resolution counts as inside the top modal layer, where `ModalRule::InDialogs` and `Blocked` @@ -897,35 +957,35 @@ fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> /// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal /// layer it opened or closed), once. fn wake_shown(ctx: &Context, viewport: ViewportId) { - let mut shown = with(ctx, |board| std::mem::take(&mut board.shown)); + let mut table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default(); let mut changed = Vec::new(); - for ((key, of), readers) in &mut shown { - if *of != viewport { - continue; - } + for (key, readers) in &mut table { // A reader beneath a layer or inside a menu that is no longer shown is gone with it. - readers.retain(|entry| match entry.reader { - Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, layer), + readers.retain(|(reader, _)| match reader { + Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer), _ => true, }); - for entry in readers.iter_mut() { + for (reader, kept) in readers.iter_mut() { // The gate is app code and may resolve commands itself, so no board lock is held here. - let (resolved, _) = resolve_as(ctx, &entry.reader, &entry.resolved.command); - if resolved != entry.resolved { - entry.resolved = resolved; + let (resolved, _) = resolve_as(ctx, reader, &kept.command); + if resolved != *kept { + *kept = resolved; changed.push(*key); } } } - shown.retain(|_, readers| !readers.is_empty()); + table.retain(|_, readers| !readers.is_empty()); with(ctx, |board| { // Reads the gate made while the entries were out of the board. - let added = std::mem::replace(&mut board.shown, shown); - for ((key, of), readers) in added { - for entry in readers { - keep_shown(&mut board.shown, key, of, entry.reader, &entry.resolved); + let added = board.shown.remove(&viewport).unwrap_or_default(); + for (key, readers) in added { + for (reader, resolved) in readers { + keep_in(table.entry(key).or_default(), reader, &resolved); } } + if !table.is_empty() { + board.shown.insert(viewport, table); + } }); for (number, instance) in changed { lazy::note_edit(ctx, BindKey::Command(number, instance)); @@ -1197,8 +1257,8 @@ pub(crate) fn begin(ctx: &Context) { board.chains.get(&viewport).filter(|(id, _)| Some(*id) == focused).map(|(_, chain)| chain.ids().collect()).unwrap_or_default() }); // Nothing focused inside a modal: the modal's root takes the commands, as a plain Enter goes to its default button. - let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.iter().find(|(of, _)| *of == viewport)) { - (true, Some((_, root))) => vec![*root], + let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.get(&viewport)) { + (true, Some(root)) => vec![*root], _ => chain, }; if !chain.is_empty() { @@ -1218,7 +1278,7 @@ pub(crate) fn begin(ctx: &Context) { } let mut keys = board.key_scopes(&chain)?; // The held-open canvas's scope is around the focus for matching: its commands fire from the dialog. - let held_scope = held_open.and_then(|id| board.instances.iter().find(|i| i.id == id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope)); + let held_scope = held_open.and_then(|id| board.instances.get(id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope)); if let Some(scope) = held_scope && !keys.scopes.contains(&scope) { @@ -1295,7 +1355,7 @@ pub(crate) fn begin(ctx: &Context) { .iter() .filter(|fired| fired.phase == FirePhase::Press) .filter_map(|fired| fired.target) - .filter_map(|target| board.instances.iter().find(|instance| instance.id == target)?.layer) + .filter_map(|target| board.instances.get(target)?.layer) .collect() }); overlay::close_popups_outside(ctx, &inside); @@ -1313,18 +1373,22 @@ pub(crate) fn end(ctx: &Context) { let alive: Vec = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect(); let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); - let ids: Vec = board.instances.iter().map(|i| i.id).collect(); - board.queue.retain(|fired| fired.target.is_some_and(|id| ids.contains(&id))); - board.held.retain(|held| held.target.is_none_or(|id| ids.contains(&id))); + let instances = &board.instances; + let ids = |id: Id| instances.contains(id); + board.queue.retain(|fired| fired.target.is_some_and(ids)); + board.held.retain(|held| held.target.is_none_or(ids)); board.chains.retain(|viewport, _| live.contains(viewport)); board.before.retain(|viewport, _| live.contains(viewport)); board.here.focused.retain(|(viewport, _)| live.contains(viewport)); - board.shown.retain(|(_, viewport), readers| { - readers.retain(|entry| match &entry.reader { - Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(|id| ids.contains(&id)), - _ => true, + board.shown.retain(|viewport, table| { + table.retain(|_, readers| { + readers.retain(|(reader, _)| match reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids), + _ => true, + }); + !readers.is_empty() }); - live.contains(viewport) && !readers.is_empty() + live.contains(viewport) && !table.is_empty() }); }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 1570c4ae1..a4cf272e8 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -19,16 +19,16 @@ pub use registry::{SetEntry, sets}; pub use board::declare_child; #[doc(hidden)] pub use board::focus_within; -#[cfg(feature = "testing")] -#[doc(hidden)] -pub use board::keymap_builds; pub(crate) use board::publish as publish_for; pub(crate) use board::take as take_for_instance; pub(crate) use board::{ - begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_delivered, take_fired, window_shortcuts, + begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts, }; #[doc(hidden)] pub use board::{bound_around, take_around}; +#[cfg(feature = "testing")] +#[doc(hidden)] +pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; use craft_behavior::CommandFlags; @@ -261,6 +261,8 @@ pub struct ResolvedCommand { pub icon: Option>, /// The chord surfaces show: the first single-press binding that runs the command ([`chord`]). pub chord: Option, + /// `chord` as the platform writes it, from the table the keymap builds with its bindings. + pub chord_text: Option>, /// The state ANDed with the gate, the modal rule and the instance's liveness. pub enabled: bool, /// The checked state of a toggle or radio command. @@ -341,7 +343,7 @@ impl CommandInput { /// The chain of container instances that receive scoped commands, innermost last. A private inherited field of /// the env. #[doc(hidden)] -#[derive(Clone, Default, PartialEq, Eq)] +#[derive(Clone, Default, PartialEq, Eq, Hash)] pub struct CommandChain(Arc<[(CommandScope, Id)]>); impl CommandChain { diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 912f37b57..71e2cf685 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -285,6 +285,18 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) } +/// Counts a chord text an access report read for a node in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_chord_text(ctx: &Context) { + totals(ctx, |log| log.chord_texts += 1); +} + +/// The chord texts the access reports of the last pass read: one per command-bound node that exists. +#[cfg(feature = "testing")] +pub fn chord_texts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.chord_texts, 0) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { @@ -347,13 +359,14 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } -/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +/// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. #[cfg(feature = "testing")] #[derive(Default)] pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, + chord_texts: u32, asks: Vec<(&'static str, u32)>, } diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index 24d76a66d..dda5a9c5f 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -219,11 +219,10 @@ impl Component for FlyoutButton<'_, T> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let laid = self.resolve(cx); - let os = cx.env.shell().os; let face = cx.part(FACE, rect).priority(HitPriority::new(HitLevel::Body, 0)); if let Some(resolved) = self.lead(&laid) { - face.tooltip(match &resolved.chord { - Some(chord) => Label::from(format!("{} ({})", resolved.label, chord.display(os))), + face.tooltip(match &resolved.chord_text { + Some(chord) => Label::from(format!("{} ({chord})", resolved.label)), None => Label::Shared(resolved.label.clone()), }); } diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index 63dfc001e..d4bb19304 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,10 +1,11 @@ -use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Tap}; +use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap}; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft_ui::runtime::commands::{ - CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, fire, resolve, + CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve, }; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::frame::take_output; +use craft_ui::runtime::measure::chord_texts; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Frames, trial}; @@ -193,3 +194,59 @@ fn undo_in_a_dialog_reaches_the_dialog_and_not_the_application() { assert_eq!(undone.get(), 1, "the dialog took the undo"); assert!(take_output(&frames.ctx).fired.is_empty(), "the application's undo stays blocked"); } + +/// Count relation: an access report reads a chord text for each command-bound node that exists, at any number of nodes, +/// never for a component with no node, and writes none; the texts are written when the keymap is built. +#[trial] +fn access_reports_read_chord_texts_for_their_nodes_and_write_none() { + let mut frames = Frames::new(); + let mut built = 0; + for count in [6, 12] { + let mut show = |ui: &mut Ui| { + for salt in 0..count { + Tap::new().id_salt(salt).command(AppCommand::Save).show(ui); + } + Tap::new().id_salt("go").command(AppCommand::Go).show(ui); + Silent::new().id_salt("silent").command(AppCommand::Save).show(ui); + }; + frames.idle(3, &mut show); + if built == 0 { + built = chord_text_builds(); + } + frames.idle(3, &mut show); + assert_eq!(chord_text_builds(), built, "passes write no chord text"); + assert_eq!(chord_texts(&frames.ctx), count, "one read per node whose command has a chord, none for a component with no node"); + } +} + +/// An instance that stops registering and registers again goes last in registration order, which a non-component +/// source's pick follows (the first live instance); lookups by id stay right throughout. +#[trial] +fn a_re_registered_instance_goes_last_in_the_pick() { + let a_shown = Cell::new(true); + let taker = Cell::new(""); + let mut show = |ui: &mut Ui| { + for name in ["a", "b", "c"] { + if name == "a" && !a_shown.get() { + continue; + } + super::kit::Pane::new().id_salt(name).show(ui, |_, cx| { + if cx.take_command::().is_some() { + taker.set(name); + } + }); + } + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette)); + frames.idle(2, &mut show); + assert_eq!(taker.get(), "a", "registered first"); + a_shown.set(false); + frames.idle(3, &mut show); + a_shown.set(true); + frames.idle(3, &mut show); + assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette)); + frames.idle(2, &mut show); + assert_eq!(taker.get(), "b", "a registered again after b and c"); +} diff --git a/crates/ui-shell/tests/it/commands/kit.rs b/crates/ui-shell/tests/it/commands/kit.rs index 0530f8cd4..551c77024 100644 --- a/crates/ui-shell/tests/it/commands/kit.rs +++ b/crates/ui-shell/tests/it/commands/kit.rs @@ -89,6 +89,37 @@ impl Component for Tap<'_> { } } +/// A `Tap` whose role gives it no access node. +#[derive(Component)] +pub struct Silent { + #[common] + common: Common, +} + +impl Silent { + pub fn new() -> Self { + Silent { common: Common::new() } + } +} + +impl Component for Silent { + const ROLE: Role = Role::None; + type Style = FixedStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: SilentStyleKey) -> FixedStyle { + FixedStyle::default() + } + + fn measure(&mut self, _: &craft_ui::contract::MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(40.0, 20.0) + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + /// A container that is an instance of the `trial.pane` scope. #[derive(Component)] #[component(container)] From 86e16f7e3b902ef674652fed10a63f063e0f3622 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 15:05:48 +0100 Subject: [PATCH 6/7] WIP: craft-automation re-exports the agents code from craft-control (#2390) From 6195b126d2e0f50507a3b892ecbed73675c618ac Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 15:14:26 +0100 Subject: [PATCH 7/7] craft-automation: re-export the agents code from craft-control (#2390) craft_automation::agents kept its own copy of the agent settings, the launcher's switch and the connection file beside craft_control::agents. It now re-exports craft-control's (and with it the CLI's live client) and keeps only the egui link host. The Agents page is unchanged. Callers see two API changes: AgentSwitch::watch takes a closure instead of craft_host::Wake, and the connection functions return std::io::Error. AgentSettings is #[non_exhaustive] in another crate now, so the trials set fields on a default instead of using struct update syntax. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 4 +- crates/automation/Cargo.toml | 12 +- crates/automation/README.md | 2 +- crates/automation/src/agents/connection.rs | 117 ------------------- crates/automation/src/agents/mod.rs | 27 +++-- crates/automation/src/agents/settings.rs | 124 --------------------- crates/automation/src/agents/switch.rs | 94 ---------------- crates/automation/tests/it/agents.rs | 17 ++- crates/control/src/agents/mod.rs | 4 +- docs/craft-framework.md | 2 +- 10 files changed, 37 insertions(+), 366 deletions(-) delete mode 100644 crates/automation/src/agents/connection.rs delete mode 100644 crates/automation/src/agents/settings.rs delete mode 100644 crates/automation/src/agents/switch.rs diff --git a/Cargo.lock b/Cargo.lock index efb9465f8..625ed4613 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2047,10 +2047,8 @@ name = "craft-automation" version = "0.1.0" dependencies = [ "base64 0.22.1", - "craft-ai-agents", - "craft-atomic", "craft-behavior", - "craft-flags", + "craft-control", "craft-host", "craft-keymap", "craft-platform", diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index f82a4c14f..9e4e079df 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -25,12 +25,15 @@ ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"] # The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`. screen-testing = ["ui", "agents", "craft-ui/testing"] # Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an -# app's `-cli mcp` reads, and with `ui` the link host and the Agents page. The agent settings -# build on every target without it. -agents = ["dep:craft-ai-agents", "dep:craft-flags", "dep:craft-atomic", "dep:craft-host"] +# app's `-cli mcp` reads and that CLI's live client (all `craft-control`'s, re-exported), and +# with `ui` the link host and the Agents page. The agent settings build on every target without it. +agents = ["craft-control/agents", "dep:craft-host"] [dependencies] craft-behavior = { workspace = true, optional = true } +# The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the +# CLI's live client), re-exported by `agents` so every app shares one copy. +craft-control = { workspace = true } craft-keymap = { workspace = true, optional = true } craft-theme = { workspace = true } craft-ui = { workspace = true, optional = true } @@ -42,9 +45,6 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] base64 = "0.22" craft-platform = { workspace = true } -craft-ai-agents = { workspace = true, optional = true } -craft-atomic = { workspace = true, optional = true } -craft-flags = { workspace = true, optional = true } craft-host = { workspace = true, optional = true } getrandom = "0.3" hmac = "0.12" diff --git a/crates/automation/README.md b/crates/automation/README.md index 1c9ff22d4..d82a01e5b 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -8,7 +8,7 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | --- | --- | | `actions` | Recorded actions (every target): `ActionList` of `Action`s and `ActionStep`s, `ActionsFile`, playback with `ActionPlayer` and `ActionRunner` under a `PlaybackBudget`, and `Recording`. The app keeps the command table. | | `ui::actions` | `ActionsPanel` (every target): sets, actions and steps as a tree, include and dialog cells, rename (`start_rename`), drag to move, Button Mode, the footer and the menus (`ActionsPanelCommands`, `ActionsMenuFacts` and `panel_rows`, which leaves out the rows the host has no command for). It runs nothing; it reports `ActionsEvent`s. `ActionsPanelState` holds its view state. `ActionsWords` holds its words. | -| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `-cli mcp` finds the open window by. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. | +| `agents` | AI agents in the open window. Every target: `AgentSettings` (Control Port, the folders agents may open from and save to, `WhenAppClosed`, Allow Agent Control) and `agents_allowed`. Desktop, feature `agents`: `AgentSwitch`, the ArtCraft Launcher's switch for the app behind the suite's `AI-MCP` flag, watched on a thread; the connection file (`Connection`, `write_connection`, `read_connection`, `remove_stale_connection`, `probe`) that the app's `-cli mcp` finds the open window by; the CLI's live client (`Live`, `LiveConfig`, `Route`). All of these are `craft_control::agents`, re-exported, so apps without the shared UI library use the same code. With `ui`: `AgentLink`, the link host that starts, moves, stops and retries the agents' control server to match the settings and publishes the connection file. | | `ui::agents` | `AgentsPage` (desktop, features `agents` and `ui`): the Agents page of Preferences, a custom page over the agent settings in the Preferences draft, with the link's status; the folder rows are `PathSetting`s. `AgentsWords` holds its words. | | `args` | `ControlOptions`: the `--control `, `--control-token`, `--control-token-file` values and their `_CONTROL_*` environment fallbacks, checked the way the apps' command lines report them (usage errors exit 2). | | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | diff --git a/crates/automation/src/agents/connection.rs b/crates/automation/src/agents/connection.rs deleted file mode 100644 index f34ee3c40..000000000 --- a/crates/automation/src/agents/connection.rs +++ /dev/null @@ -1,117 +0,0 @@ -//! The connection file: where an app's control server listens for agents. - -use std::net::{SocketAddr, TcpStream}; -use std::path::{Path, PathBuf}; -use std::time::Duration; - -use serde::{Deserialize, Serialize}; - -use crate::AutomationError; - -/// The connection file in the app's settings folder, present while the app accepts agents. -pub const CONNECTION_FILE: &str = "agent-connection.json"; -/// The token file the app keeps in its settings folder for agent connections. -pub const TOKEN_FILE: &str = "agent-control.token"; -/// How long [`probe`] waits for a connection to be accepted. -pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); -/// The version of the [`Connection`] file format. -const CONNECTION_VERSION: u32 = 1; -/// The largest connection file read; anything bigger is not one. -const MAX_CONNECTION_BYTES: u64 = 1 << 20; - -/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`. -/// Holds no secret: the token stays in its own owner-only file. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Connection { - /// The file format's version (1). - pub version: u32, - /// The app's process id: only that process removes the file. - pub pid: u32, - /// The loopback port of the control server. - pub port: u16, - /// The file holding the token. - pub token_file: PathBuf, - /// The app's version, for diagnostics. - pub app: String, -} - -impl Connection { - /// This process's connection on `port`, naming `app` (the app's version string). - pub fn new(port: u16, token_file: PathBuf, app: impl Into) -> Self { - Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() } - } - - /// `127.0.0.1:`. - pub fn addr(&self) -> String { - format!("127.0.0.1:{}", self.port) - } -} - -fn io_error(path: &Path, e: impl std::fmt::Display) -> AutomationError { - AutomationError::Io(format!("{}: {e}", path.display())) -} - -/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a -/// file. -pub fn write_connection(dir: &Path, c: &Connection) -> Result<(), AutomationError> { - std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; - let path = dir.join(CONNECTION_FILE); - let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?; - craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) -} - -/// The connection published in `dir`, if any. A file of another version, with port 0, or one -/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next -/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over -/// 1 MiB is an error, and left alone. -pub fn read_connection(dir: &Path) -> Result, AutomationError> { - let path = dir.join(CONNECTION_FILE); - let meta = match std::fs::metadata(&path) { - Ok(m) => m, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(e) => return Err(io_error(&path, e)), - }; - if !meta.is_file() { - return Err(io_error(&path, "not a regular file")); - } - if meta.len() > MAX_CONNECTION_BYTES { - return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); - } - let bytes = match std::fs::read(&path) { - Ok(b) => b, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(e) => return Err(io_error(&path, e)), - }; - Ok(serde_json::from_slice::(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) -} - -/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have -/// published its own since). Errors are ignored: a stale file only fails [`probe`]. -pub fn remove_connection(dir: &Path, pid: u32) { - if let Ok(Some(c)) = read_connection(dir) - && c.pid == pid - { - let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); - } -} - -/// Removes the connection file in `dir` when nothing listens on its port any more (an app that -/// crashed or quit without removing it), or when it does not read as a connection. A live -/// instance's file is kept, and so is anything but a regular file. Errors are ignored. -pub fn remove_stale_connection(dir: &Path) { - let path = dir.join(CONNECTION_FILE); - let stale = match read_connection(dir) { - Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT), - Ok(None) => path.is_file(), - Err(_) => false, - }; - if stale { - let _ = std::fs::remove_file(path); - } -} - -/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does. -pub fn probe(port: u16, timeout: Duration) -> bool { - port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() -} diff --git a/crates/automation/src/agents/mod.rs b/crates/automation/src/agents/mod.rs index 949740ed8..0ff21d3a8 100644 --- a/crates/automation/src/agents/mod.rs +++ b/crates/automation/src/agents/mod.rs @@ -9,8 +9,8 @@ //! While agents may connect, the app serves its control channel on loopback ([`AgentLink`], over //! [`crate::server`]) and publishes where in its settings folder ([`CONNECTION_FILE`]): the port, //! its process id and the token file ([`TOKEN_FILE`], created `0600` on Unix). The app's -//! `-cli mcp` reads that file on every tool call, then the token from the file it names, so an -//! MCP client's configuration never holds a port or a token. +//! `-cli mcp` reads that file on every tool call ([`Live`]), then the token from the file it +//! names, so an MCP client's configuration never holds a port or a token. //! //! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then //! listens on its port ([`probe`]), and the app's next launch removes it @@ -18,29 +18,32 @@ //! checks that [`Connection::pid`] is still running before it sends anything derived from the //! token, and authenticates with the challenge handshake ([`crate::security::ServerHandshake`]). //! +//! Everything but the link host is `craft_control::agents`, re-exported here: apps that don't use +//! the shared UI library use it from there, with the same files and formats. +//! //! | Part | Names | Builds | //! |---|---|---| //! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target | //! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` | //! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | +//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | //! | The link host | [`AgentLink`], [`AgentLinkStatus`], [`LinkProblem`], [`LinkUpdate`] | desktop, features `agents` and `ui` | //! //! The Agents page of Preferences is [`crate::ui::agents`]. -mod settings; -pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder}; +// The links above name items of the `agents` and `ui` features; without them they have nothing to +// point at, and the docs of the settings alone still build. +#![cfg_attr(not(all(feature = "agents", feature = "ui", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))] + +pub use craft_control::agents::{AgentSettings, WhenAppClosed, agents_allowed, folder}; -#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] -mod connection; #[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))] mod link; #[cfg(all(feature = "agents", not(target_arch = "wasm32")))] -mod switch; -#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] -pub use connection::{ - CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection, +pub use craft_control::agents::{ + AgentSwitch, CONNECTION_FILE, ConnectFn, Connection, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn, + Live, LiveConfig, POLL, PROBE_TIMEOUT, Route, TOKEN_FILE, Window, find_window, launcher, launcher_allows, mcp_flag, probe, read_connection, + remove_connection, remove_stale_connection, write_connection, }; #[cfg(all(feature = "agents", feature = "ui", not(target_arch = "wasm32")))] pub use link::{AgentLink, AgentLinkStatus, LinkProblem, LinkUpdate, RETRY}; -#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] -pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag}; diff --git a/crates/automation/src/agents/settings.rs b/crates/automation/src/agents/settings.rs deleted file mode 100644 index 1b5918759..000000000 --- a/crates/automation/src/agents/settings.rs +++ /dev/null @@ -1,124 +0,0 @@ -//! The agent settings an app saves in its preferences, and who decides that agents may connect. - -use std::path::PathBuf; - -use serde::{Deserialize, Serialize}; - -/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in -/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`. -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default, rename_all = "camelCase")] -#[non_exhaustive] -pub struct AgentSettings { - /// Off refuses every control server, `--control` included. - pub allow_agent_control: bool, - /// The loopback port agents connect to; 0 is any free port, published in the connection file. - pub control_port: u32, - /// The folder agents may open from; empty is none. Applied at once while agents are connected. - pub read_root: String, - /// The folder agents may save to; empty is none. Applied at once while agents are connected. - pub write_root: String, - /// What the app's `-cli mcp` does while agents may use the app but it is closed. - pub when_app_closed: WhenAppClosed, -} - -impl Default for AgentSettings { - fn default() -> Self { - Self { - allow_agent_control: true, - control_port: 0, - read_root: String::new(), - write_root: String::new(), - when_app_closed: WhenAppClosed::Launch, - } - } -} - -impl AgentSettings { - /// [`Self::read_root`] as a path ([`folder`]). - pub fn read_folder(&self) -> Option { - folder(&self.read_root) - } - - /// [`Self::write_root`] as a path ([`folder`]). - pub fn write_folder(&self) -> Option { - folder(&self.write_root) - } -} - -/// A folder setting as a path, trimmed; empty or blank is `None`. -pub fn folder(pref: &str) -> Option { - let pref = pref.trim(); - (!pref.is_empty()).then(|| PathBuf::from(pref)) -} - -/// What an app's `-cli mcp` does when an agent calls a tool while the app is closed. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum WhenAppClosed { - /// Open the app and wait for it. - #[default] - Launch, - /// Run the tool without a window. - Headless, - /// Answer with an error that asks to open the app. - Error, -} - -impl WhenAppClosed { - /// The saved names, in [`Self::ALL`] order. - pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"]; - /// Every choice, in the order a menu lists them. - pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error]; - - /// The saved name. - pub fn name(self) -> &'static str { - match self { - Self::Launch => "launch", - Self::Headless => "headless", - Self::Error => "error", - } - } - - /// The choice a saved name means; `None` for any other text. - pub fn parse(name: &str) -> Option { - Self::ALL.into_iter().find(|c| c.name() == name) - } -} - -/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's -/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own -/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch). -/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]). -pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool { - if mcp_flag { launcher } else { legacy } -} - -#[cfg(test)] -mod tests { - use super::*; - use craft_ui::testing::trial; - - // The saved names read back as the same choice, and nothing else reads as one. - #[trial] - fn when_app_closed_names_round_trip() { - for choice in WhenAppClosed::ALL { - assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice)); - assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name())); - } - assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name)); - assert_eq!(WhenAppClosed::parse("Launch"), None); - let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap(); - assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true)); - } - - // A folder setting is trimmed; empty or blank means no folder. - #[trial] - fn folder_preferences_are_trimmed() { - assert_eq!(folder(""), None); - assert_eq!(folder(" "), None); - assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project"))); - let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() }; - assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None)); - } -} diff --git a/crates/automation/src/agents/switch.rs b/crates/automation/src/agents/switch.rs deleted file mode 100644 index 28af63d83..000000000 --- a/crates/automation/src/agents/switch.rs +++ /dev/null @@ -1,94 +0,0 @@ -//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag. - -use std::sync::atomic::{AtomicBool, Ordering}; -use std::sync::{Arc, Weak}; -use std::time::Duration; - -use craft_host::Wake; - -use super::agents_allowed; - -/// How often [`AgentSwitch::watch`] reads the launcher's app list. -pub const POLL: Duration = Duration::from_secs(2); - -/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file; -/// what could not be read is logged. -pub fn mcp_flag() -> bool { - let flags = craft_flags::load(); - for problem in &flags.problems { - log::warn!("flags: {problem}"); - } - flags.enabled(&craft_flags::AI_MCP) -} - -/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use -/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two -/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that). -pub fn launcher_allows(app_id: &str) -> bool { - mcp_flag() && craft_ai_agents::allowed(app_id) -} - -/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the -/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`]. -/// Clones share one watch; the thread ends after the last clone is dropped. -#[derive(Clone, Debug)] -pub struct AgentSwitch { - mcp_flag: bool, - on: Arc, -} - -impl AgentSwitch { - /// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake`. - /// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then. - pub fn watch(app_id: &'static str, wake: Wake) -> Self { - let flag = mcp_flag(); - if !flag { - return Self::fixed(false, false); - } - Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) - } - - /// A switch that never changes: tests, the web, an app without agents. - pub fn fixed(mcp_flag: bool, launcher: bool) -> Self { - Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } - } - - /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. - #[doc(hidden)] - pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: Wake) -> Self { - let on = Arc::new(AtomicBool::new(probe())); - let seen: Weak = Arc::downgrade(&on); - let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { - loop { - std::thread::sleep(poll); - let now = probe(); - let Some(seen) = seen.upgrade() else { return }; - if seen.swap(now, Ordering::Relaxed) != now { - log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" }); - wake.wake(); - } - } - }); - // Without a thread the answer stays what it was at launch. - if let Err(e) = started { - log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}"); - } - Self { mcp_flag, on } - } - - /// The `AI-MCP` flag as it was when the watch started. - pub fn mcp_flag(&self) -> bool { - self.mcp_flag - } - - /// Whether the launcher's list named the app at the last poll. - pub fn launcher(&self) -> bool { - self.on.load(Ordering::Relaxed) - } - - /// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own - /// earlier consent, which counts only without the flag. - pub fn allows(&self, legacy: bool) -> bool { - agents_allowed(self.mcp_flag, self.launcher(), legacy) - } -} diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 2ffb2b5e6..7ca7bb5f0 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -14,7 +14,7 @@ use craft_automation::agents::{ }; use craft_automation::server; use craft_automation::ui::agents::AgentsPage; -use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles, Wake}; +use craft_host::{AppInfo, Host, PickId, Picked, ScriptedFiles}; use craft_ui::contract::Role; use craft_ui::patterns::preferences::SettingsDraft; use craft_ui::runtime::motion; @@ -68,9 +68,9 @@ fn the_switch_wakes_once_per_change() { }; let wake = { let wakes = wakes.clone(); - Wake::new(move || { + move || { wakes.fetch_add(1, Ordering::Relaxed); - }) + } }; let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); let clone = switch.clone(); @@ -161,7 +161,9 @@ fn host() -> WindowHost { } fn on(port: u32) -> AgentSettings { - AgentSettings { control_port: port, ..AgentSettings::default() } + let mut s = AgentSettings::default(); + s.control_port = port; + s } /// A port nothing listens on: bound, then closed. @@ -188,7 +190,8 @@ fn turning_agents_on_publishes_a_reachable_connection_and_off_removes_it() { assert!(probe(port, PROBE_TIMEOUT)); let token = std::fs::read_to_string(dir.path().join(TOKEN_FILE)).unwrap(); - let folders = AgentSettings { read_root: "/in".into(), ..on(0) }; + let mut folders = on(0); + folders.read_root = "/in".into(); let kept = link.sync(Some(&folders), &host); assert!(kept.requests.is_none() && !kept.stopped && kept.changed, "a folder change keeps the server"); assert_eq!(link.status().port, Some(port)); @@ -266,7 +269,9 @@ fn allow_agent_control_off_and_no_settings_folder_keep_agents_out() { let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); assert!(link.sync(Some(&on(0)), &host).requests.is_some()); let port = link.status().port.expect("listening"); - let refused = link.sync(Some(&AgentSettings { allow_agent_control: false, ..on(0) }), &host); + let mut off = on(0); + off.allow_agent_control = false; + let refused = link.sync(Some(&off), &host); assert!(refused.stopped && refused.requests.is_none()); assert_eq!(link.status().problem, Some(LinkProblem::NotAllowed)); assert!(!dir.path().join(CONNECTION_FILE).exists()); diff --git a/crates/control/src/agents/mod.rs b/crates/control/src/agents/mod.rs index e1b0b9923..17581cd8e 100644 --- a/crates/control/src/agents/mod.rs +++ b/crates/control/src/agents/mod.rs @@ -23,8 +23,8 @@ //! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | //! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | //! -//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`), -//! which adds the egui link host and the Agents page of Preferences. +//! `craft_automation::agents` re-exports all of this and adds the egui link host and the Agents +//! page of Preferences, for apps on the shared UI library. //! //! # Adding an app //! diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 2e3e52874..dff78e213 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -1123,7 +1123,7 @@ Control channel, screenshot queue, profiler and recorded actions for tests and s | `protocol` | JSON-lines wire format and parameter validators | exists | | `security` | Tokens, the authentication handshake (challenge or one-frame token) and transport limits | exists | | `server` | Loopback JSON-lines TCP transport (native): `listen`, `serve`, stopped by dropping its `Listening` | exists | -| `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file, the link host and the Agents page of Preferences | exists | +| `agents`, `ui::agents` | AI agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and the CLI's live client (re-exported from `craft-control`), the link host and the Agents page of Preferences | exists | | `client` | JSON-lines client for tests and command-line tools (native) | exists | | `synthetic` | Synthetic pointer and keyboard input: `ui.click`, `ui.move`, `ui.key`, `ui.type` | exists | | `dialogs` | `ui.dialog.set`, `ui.dialog.confirm` and `ui.dialog.cancel` over a `DialogHost` | exists |