SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agent chat: Pick context and Attach selection for elements, features and bodies (#2286) (#2288)
Rec0iLd5a79a77e6f9
diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 043a04349c..5b7d6d4ee4 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -2227,6 +2227,8 @@"ui.agent_chat_allowed": "Allowed","ui.agent_chat_answered": "Answer: {option}","ui.agent_chat_approval": "Allow the agent to do this?",+ "ui.agent_chat_attach_selection": "Attach selection",+ "ui.agent_chat_attach_selection_tip": "Send what is selected in the model (faces, edges, features, bodies) with the message, so the agent knows what you mean","ui.agent_chat_attach_view": "Attach view","ui.agent_chat_attach_view_tip": "Send a picture of the current view with the message","ui.agent_chat_attachable": "Pictures, PDFs, text and CAD files",@@ -2244,6 +2246,11 @@"ui.agent_chat_command": "Agent command","ui.agent_chat_connect": "Connect","ui.agent_chat_copy": "Copy",+ "ui.agent_chat_ctx_bodies": "Bodies",+ "ui.agent_chat_ctx_elements": "Elements",+ "ui.agent_chat_ctx_features": "Features",+ "ui.agent_chat_ctx_more": "+{n} more",+ "ui.agent_chat_ctx_other": "Other","ui.agent_chat_custom_hint": "Any program that speaks the Agent Client Protocol on stdin and stdout. No shell runs it.","ui.agent_chat_denied": "Denied","ui.agent_chat_deny": "Deny",@@ -2302,6 +2309,8 @@"ui.agent_chat_paste_picture": "Paste a picture","ui.agent_chat_permission": "The agent asks to run: {title}","ui.agent_chat_pick": "Agent",+ "ui.agent_chat_pick_context": "Pick context",+ "ui.agent_chat_pick_context_tip": "Choose faces, edges, features and bodies in the model for the agent to look at, then press OK","ui.agent_chat_placeholder": "Ask the agent to change the design…","ui.agent_chat_placeholder_busy": "Queue a message for when the agent is done (Ctrl+Enter: send now)","ui.agent_chat_pop_out": "Open in its own window, which you can move to another screen",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 870f06158c..b4b287a052 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -2227,6 +2227,8 @@"ui.agent_chat_allowed": "許可しました","ui.agent_chat_answered": "回答: {option}","ui.agent_chat_approval": "エージェントにこの操作を許可しますか?",+ "ui.agent_chat_attach_selection": "選択を添付",+ "ui.agent_chat_attach_selection_tip": "モデルで選択中のもの(面、エッジ、フィーチャ、ボディ)をメッセージと一緒に送り、何を指しているかをエージェントに伝えます","ui.agent_chat_attach_view": "ビューを添付","ui.agent_chat_attach_view_tip": "現在のビューの画像をメッセージと一緒に送ります","ui.agent_chat_attachable": "画像・PDF・テキスト・CAD ファイル",@@ -2244,6 +2246,11 @@"ui.agent_chat_command": "エージェントのコマンド","ui.agent_chat_connect": "接続","ui.agent_chat_copy": "コピー",+ "ui.agent_chat_ctx_bodies": "ボディ",+ "ui.agent_chat_ctx_elements": "要素",+ "ui.agent_chat_ctx_features": "フィーチャ",+ "ui.agent_chat_ctx_more": "ほか{n}件",+ "ui.agent_chat_ctx_other": "その他","ui.agent_chat_custom_hint": "標準入出力で Agent Client Protocol を話す任意のプログラム。シェルは使いません。","ui.agent_chat_denied": "拒否しました","ui.agent_chat_deny": "拒否",@@ -2302,6 +2309,8 @@"ui.agent_chat_paste_picture": "画像を貼り付け","ui.agent_chat_permission": "エージェントが実行の許可を求めています: {title}","ui.agent_chat_pick": "エージェント",+ "ui.agent_chat_pick_context": "コンテキストを選ぶ",+ "ui.agent_chat_pick_context_tip": "エージェントに見てほしい面、エッジ、フィーチャ、ボディをモデルから選び、OK を押します","ui.agent_chat_placeholder": "デザインの変更をエージェントに依頼…","ui.agent_chat_placeholder_busy": "エージェントの作業が終わったら送るメッセージを入力(Ctrl+Enter: 今すぐ送信)","ui.agent_chat_pop_out": "独立したウィンドウで開く(別の画面に移動できます)",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex 4e27fb27f0..537fa31ba9 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -2227,6 +2227,8 @@"ui.agent_chat_allowed": "已允许","ui.agent_chat_answered": "回答:{option}","ui.agent_chat_approval": "允许智能体执行此操作吗?",+ "ui.agent_chat_attach_selection": "附加选择",+ "ui.agent_chat_attach_selection_tip": "随消息发送模型中当前选中的内容(面、边、特征、实体),让智能体知道你指的是什么","ui.agent_chat_attach_view": "附加视图","ui.agent_chat_attach_view_tip": "随消息发送当前视图的图片","ui.agent_chat_attachable": "图片、PDF、文本和 CAD 文件",@@ -2244,6 +2246,11 @@"ui.agent_chat_command": "智能体命令","ui.agent_chat_connect": "连接","ui.agent_chat_copy": "复制",+ "ui.agent_chat_ctx_bodies": "实体",+ "ui.agent_chat_ctx_elements": "元素",+ "ui.agent_chat_ctx_features": "特征",+ "ui.agent_chat_ctx_more": "另有 {n} 项",+ "ui.agent_chat_ctx_other": "其他","ui.agent_chat_custom_hint": "任何通过标准输入输出使用 Agent Client Protocol 的程序。不经过 shell 运行。","ui.agent_chat_denied": "已拒绝","ui.agent_chat_deny": "拒绝",@@ -2302,6 +2309,8 @@"ui.agent_chat_paste_picture": "粘贴图片","ui.agent_chat_permission": "智能体请求运行:{title}","ui.agent_chat_pick": "智能体",+ "ui.agent_chat_pick_context": "选择上下文",+ "ui.agent_chat_pick_context_tip": "在模型中选择要让智能体查看的面、边、特征和实体,然后点击确定","ui.agent_chat_placeholder": "让智能体修改设计…","ui.agent_chat_placeholder_busy": "输入消息,待智能体完成后发送(Ctrl+Enter:立即发送)","ui.agent_chat_pop_out": "在独立窗口中打开(可移到另一个屏幕)",diff --git a/crates/ui-egui/src/agent_chat/context.rs b/crates/ui-egui/src/agent_chat/context.rsnew file mode 100644index 0000000000..d93c5a55f8--- /dev/null+++ b/crates/ui-egui/src/agent_chat/context.rs@@ -0,0 +1,380 @@+//! What the user had selected in the model, as context for a message ("Attach selection", #2286).+//! The selection is described when the message is sent: faces and edges with the names and+//! numbers the agent's tools take (and a size and place that survive an edit), features by name and+//! kind, bodies by name. The conversation shows the same items as chips; the agent gets them as a+//! block of text after the message.++use std::collections::HashMap;++use serde_json::{Value, json};+use solidcraft_engine::geom::Vec3;+use solidcraft_engine::{Sel, Session};++/// The most items one message carries; the rest are counted, not dropped silently.+pub const MAX_ITEMS: usize = 64;++/// What an item is, for grouping the chips: a face, edge or vertex; a step of the timeline; a body+/// or a placed component; anything else (planes, axes, sketch geometry).+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]+pub enum Kind {+ Element,+ Feature,+ Body,+ Other,+}++impl Kind {+ pub const ALL: [Kind; 4] = [Kind::Element, Kind::Feature, Kind::Body, Kind::Other];++ /// The message id of the group's heading.+ pub fn heading(self) -> &'static str {+ match self {+ Kind::Element => "ui.agent_chat_ctx_elements",+ Kind::Feature => "ui.agent_chat_ctx_features",+ Kind::Body => "ui.agent_chat_ctx_bodies",+ Kind::Other => "ui.agent_chat_ctx_other",+ }+ }++ fn english(self) -> &'static str {+ match self {+ Kind::Element => "Elements",+ Kind::Feature => "Features",+ Kind::Body => "Bodies",+ Kind::Other => "Other",+ }+ }+}++/// One selected thing: its short name for a chip, and what is known about it.+#[derive(Clone, Debug, PartialEq)]+pub struct Entry {+ pub kind: Kind,+ pub label: String,+ pub detail: String,+}++/// The things a message was sent with.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Context {+ pub items: Vec<Entry>,+ /// Selected things past [`MAX_ITEMS`], not described.+ pub omitted: usize,+}++impl Context {+ pub fn is_empty(&self) -> bool {+ self.items.is_empty() && self.omitted == 0+ }++ /// Everything counted, listed or not.+ pub fn total(&self) -> usize {+ self.items.len() + self.omitted+ }++ /// Add the items of another message (queued messages go as one prompt), up to the limit.+ pub fn merge(&mut self, other: Context) {+ self.omitted += other.omitted;+ for item in other.items {+ if self.items.len() < MAX_ITEMS {+ self.items.push(item);+ } else {+ self.omitted += 1;+ }+ }+ }++ /// The block of text the agent gets after the message, `""` when nothing was selected.+ pub fn prompt_block(&self) -> String {+ if self.is_empty() {+ return String::new();+ }+ let mut out = format!(+ "[Selected in SolidCraft when this message was sent: {} item(s). The names, indices and points are the ones the tools take.]",+ self.total()+ );+ for kind in Kind::ALL {+ let mut lines = self.items.iter().filter(|i| i.kind == kind).peekable();+ if lines.peek().is_none() {+ continue;+ }+ out.push_str(&format!("\n{}:", kind.english()));+ for item in lines {+ out.push_str(&format!("\n- {}", item.label));+ if !item.detail.is_empty() {+ out.push_str(&format!(": {}", item.detail));+ }+ }+ }+ if self.omitted > 0 {+ out.push_str(&format!("\n(and {} more, not listed)", self.omitted));+ }+ out+ }+}++/// The message as the agent gets it: the text, then what was selected.+pub fn with_context(text: &str, context: &Context) -> String {+ let block = context.prompt_block();+ if block.is_empty() { text.to_string() } else { format!("{text}\n\n{block}") }+}++/// Describe what the session has selected, as what was clicked: see [`clicked`].+pub fn describe_selection(session: &mut Session) -> Context {+ let groups = clicked(session, &session.selection.clone());+ describe_groups(session, &groups)+}++/// How many things were clicked to make a selection: the pieces a click on a rim or on a surface+/// split by a seam selects count once.+pub fn selection_count(session: &Session, selection: &[Sel]) -> usize {+ clicked(session, selection).len()+}++/// A selection as the things the user clicked. A click on a circular rim or a split surface selects+/// all its pieces (so commands get them all); here they are one group, the clicked piece first.+/// Past [`MAX_GROUPING`] items the selection is taken as it is: nobody clicked that many rims.+pub fn clicked(session: &Session, selection: &[Sel]) -> Vec<Vec<Sel>> {+ let mut groups: Vec<Vec<Sel>> = Vec::new();+ let mut taken = vec![false; selection.len()];+ for (i, sel) in selection.iter().enumerate() {+ if taken[i] {+ continue;+ }+ let mut group = vec![sel.clone()];+ if selection.len() <= MAX_GROUPING && matches!(sel, Sel::Edge { .. } | Sel::Face { .. }) {+ for piece in crate::viewport::grouped_selection(session, sel) {+ if let Some(j) = selection.iter().enumerate().position(|(j, x)| j != i && !taken[j] && crate::selection::same_item(x, &piece)) {+ taken[j] = true;+ group.push(selection[j].clone());+ }+ }+ }+ groups.push(group);+ }+ groups+}++/// More than this many selected things are not grouped into clicks (each grouping reads the model).+const MAX_GROUPING: usize = 256;++/// Describe a selection, each item on its own: what the picker holds. Face and edge details come+/// from the model's own listings (`model.faces`, `model.edges`), asked once per body.+pub fn describe(session: &mut Session, selection: &[Sel]) -> Context {+ let groups: Vec<Vec<Sel>> = selection.iter().map(|s| vec![s.clone()]).collect();+ describe_groups(session, &groups)+}++/// Describe groups of pieces that were clicked as one thing, each once.+pub fn describe_groups(session: &mut Session, groups: &[Vec<Sel>]) -> Context {+ let mut context = Context::default();+ let mut listings: HashMap<(&'static str, String), Value> = HashMap::new();+ for group in groups {+ if context.items.len() >= MAX_ITEMS {+ context.omitted += 1;+ } else if let Some(first) = group.first() {+ let mut item = entry(session, first, &mut listings);+ if group.len() > 1 {+ join_pieces(session, group, &mut item, &mut listings);+ }+ context.items.push(item);+ }+ }+ context+}++/// An item clicked as several pieces (the halves of a rim, the patches of a split surface): one+/// entry with the whole size, and what the tools take for every piece in its detail.+fn join_pieces(session: &mut Session, group: &[Sel], item: &mut Entry, listings: &mut HashMap<(&'static str, String), Value>) {+ let mut sizes = Vec::new();+ let mut indices = Vec::new();+ let mut names = Vec::new();+ let mut unit = "";+ let mut body = String::new();+ for sel in group {+ let found = match sel {+ Sel::Edge { body: b, index, point } => {+ unit = "mm";+ body = b.clone();+ indices.push(*index);+ listed_edge(session, listings, b, *index, *point)+ }+ Sel::Face { body: b, index, .. } => {+ unit = "mm²";+ body = b.clone();+ indices.push(*index);+ listed(session, listings, "model.faces", "faces", b, *index)+ }+ _ => None,+ };+ if let Some(f) = found {+ if let Some(n) = f["name"].as_str() {+ names.push(n.to_string());+ }+ if let Some(v) = f[if unit == "mm" { "length" } else { "area" }].as_f64() {+ sizes.push(v);+ }+ }+ }+ let pieces = group.len();+ let total: f64 = sizes.iter().sum();+ if matches!(group.first(), Some(Sel::Edge { .. })) && sizes.len() == pieces {+ item.label = format!("Edge {} mm ({pieces} pieces) · {body}", num(total));+ } else {+ item.label = format!("{} ({pieces} pieces)", item.label);+ }+ let whole = if sizes.len() == pieces { format!(", total {} {unit}", num(total)) } else { String::new() };+ let names = if names.is_empty() { String::new() } else { format!(", names {}", names.join(" + ")) };+ item.detail = format!("clicked as one: {pieces} pieces, indices {indices:?}{names}{whole}; first piece: {}", item.detail);+}++fn entry(session: &mut Session, sel: &Sel, listings: &mut HashMap<(&'static str, String), Value>) -> Entry {+ match sel {+ Sel::Face { body, index, point } => {+ let face = listed(session, listings, "model.faces", "faces", body, *index);+ let mut parts = Vec::new();+ // A name a person can read: the shape and its size, then the body. What the tools take+ // (the persistent name, the index, the pick point) is in the detail.+ let mut shape = format!("Face #{index}");+ if let Some(f) = &face {+ let radius = f["cylinder"]["radius"].as_f64();+ let planar = f["plane_normal"].is_array();+ let area = f["area"].as_f64().map(|a| format!(" {} mm²", num(a))).unwrap_or_default();+ shape = match (radius, planar) {+ (Some(r), _) => format!("Round face r{}", num(r)),+ (None, true) => format!("Flat face{area}"),+ _ => format!("Curved face{area}"),+ };+ if let Some(name) = f["name"].as_str() {+ parts.push(format!("name {name}"));+ }+ parts.push(match (radius, planar) {+ (Some(r), _) => format!("cylindrical, radius {} mm", num(r)),+ (None, true) => format!("planar, normal {}", point3(&f["plane_normal"])),+ _ => "curved".to_string(),+ });+ if let Some(a) = f["area"].as_f64() {+ parts.push(format!("area {} mm²", num(a)));+ }+ parts.push(format!("centroid {}", point3(&f["centroid"])));+ parts.push(format!("index {index}"));+ }+ parts.push(format!("pick point {}", point3(&json!(point))));+ Entry { kind: Kind::Element, label: format!("{shape} · {body}"), detail: parts.join(", ") }+ }+ Sel::Edge { body, index, point } => {+ let edge = listed_edge(session, listings, body, *index, *point);+ let mut parts = Vec::new();+ let mut shape = format!("Edge #{index}");+ if let Some(e) = &edge {+ if let Some(name) = e["name"].as_str() {+ parts.push(format!("name {name}"));+ }+ if let Some(l) = e["length"].as_f64() {+ shape = format!("Edge {} mm", num(l));+ parts.push(format!("length {} mm", num(l)));+ }+ parts.push(format!("from {} to {}", point3(&e["start"]), point3(&e["end"])));+ parts.push(format!("index {index}"));+ }+ parts.push(format!("pick point {}", point3(&json!(point))));+ Entry { kind: Kind::Element, label: format!("{shape} · {body}"), detail: parts.join(", ") }+ }+ Sel::Vertex { body, point } => {+ Entry { kind: Kind::Element, label: format!("Vertex of {body}"), detail: format!("at {}", point3(&json!(point))) }+ }+ Sel::Body { name } => Entry { kind: Kind::Body, label: name.clone(), detail: String::new() },+ Sel::Occurrence { path } => Entry {+ kind: Kind::Body,+ label: format!("Component occurrence {}", path.iter().map(u64::to_string).collect::<Vec<_>>().join("/")),+ detail: format!("occurrence path {path:?}"),+ },+ Sel::Feature { id } => {+ let feature = session.doc.find_feature(&id.to_string());+ let name = feature.map(|f| f.name.clone()).unwrap_or_else(|| format!("#{id}"));+ let kind = feature.and_then(|f| serde_json::to_value(f).ok()).and_then(|v| v["type"].as_str().map(str::to_string));+ let mut detail = format!("feature id {id}");+ if let Some(kind) = kind {+ detail = format!("{kind}, {detail}");+ }+ if feature.is_some_and(|f| f.suppressed) {+ detail.push_str(", suppressed");+ }+ Entry { kind: Kind::Feature, label: name, detail }+ }+ other => {+ // Planes, axes and sketch geometry: named by their kind and whatever identifies them.+ let value = serde_json::to_value(other).unwrap_or(Value::Null);+ let kind = value["type"].as_str().unwrap_or("item").replace('_', " ");+ let id = ["name", "id", "index", "sketch"].iter().find_map(|k| match &value[k] {+ Value::String(s) => Some(s.clone()),+ Value::Number(n) => Some(n.to_string()),+ _ => None,+ });+ let label = match id {+ Some(id) => format!("{kind} {id}"),+ None => kind,+ };+ let label: String = label.chars().take(60).collect();+ Entry { kind: Kind::Other, label: capitalised(&label), detail: String::new() }+ }+ }+}++/// The listing entry for a face or edge (`index`), from a command run once per body.+fn listed(+ session: &mut Session,+ listings: &mut HashMap<(&'static str, String), Value>,+ command: &'static str,+ list: &str,+ body: &str,+ index: usize,+) -> Option<Value> {+ let listing =+ listings.entry((command, body.to_string())).or_insert_with(|| session.execute(command, &json!({"body": body})).unwrap_or(Value::Null));+ let index = u64::try_from(index).ok()?;+ listing[list].as_array()?.iter().find(|item| item["index"].as_u64() == Some(index)).cloned()+}++/// The listing entry of the edge picked at `point`: the one with that index, unless its middle is+/// somewhere else (the selection and the listing number edges alike, but a stale index must not+/// describe another edge), then the edge whose middle is nearest the point.+fn listed_edge(session: &mut Session, listings: &mut HashMap<(&'static str, String), Value>, body: &str, index: usize, point: Vec3) -> Option<Value> {+ let by_index = listed(session, listings, "model.edges", "edges", body, index);+ let near = |e: &Value| -> Option<f64> {+ let mid = e["mid"].as_array()?;+ let p = |i: usize| mid.get(i).and_then(Value::as_f64);+ let dist = ((p(0)? - point.x).powi(2) + (p(1)? - point.y).powi(2) + (p(2)? - point.z).powi(2)).sqrt();+ dist.is_finite().then_some(dist)+ };+ let tolerance = |e: &Value| (0.02 * e["length"].as_f64().unwrap_or(0.0)).max(0.05);+ if let Some(e) = &by_index+ && near(e).is_some_and(|d| d <= tolerance(e))+ {+ return by_index;+ }+ let all = listings.get(&("model.edges", body.to_string()))?["edges"].as_array()?.clone();+ all.into_iter().filter_map(|e| near(&e).map(|d| (d, e))).filter(|(d, e)| *d <= tolerance(e)).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, e)| e)+}++/// A length or area to two decimals, without a trailing `.00`.+fn num(v: f64) -> String {+ if !v.is_finite() {+ return "?".into();+ }+ let s = format!("{v:.2}");+ s.trim_end_matches('0').trim_end_matches('.').to_string()+}++/// `(x, y, z)` from a JSON array of three numbers, `?` when it is not one.+fn point3(v: &Value) -> String {+ match v.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect::<Vec<_>>()) {+ Some(c) if c.len() == 3 => format!("({}, {}, {})", num(c[0]), num(c[1]), num(c[2])),+ _ => "?".into(),+ }+}++fn capitalised(s: &str) -> String {+ let mut chars = s.chars();+ chars.next().map(|c| c.to_uppercase().chain(chars).collect()).unwrap_or_default()+}diff --git a/crates/ui-egui/src/agent_chat/mod.rs b/crates/ui-egui/src/agent_chat/mod.rsindex 9b0d6a7384..e10143513c 100644--- a/crates/ui-egui/src/agent_chat/mod.rs+++ b/crates/ui-egui/src/agent_chat/mod.rs@@ -24,6 +24,7 @@ pub mod agents;mod api_client;pub mod attach;pub mod backend;+pub mod context;#[cfg(not(target_arch = "wasm32"))]pub mod discover;pub mod gate;@@ -41,6 +42,8 @@ use std::sync::mpsc::{Receiver, Sender};use serde_json::{Value, json};+use context::Context;+use crate::i18n::{format as trf, tr};use crate::{ControlRequest, SolveApp};use backend::{ChatBackend, Event, PermissionOption, PromptPart, ToolStatus};@@ -195,6 +198,8 @@ pub enum Item {image: bool,/// The view's picture, kept once it is taken (when the agent starts on the message).pictures: Vec<Picture>,+ /// What was selected or picked in the model when it was sent ("Attach selection", Pick context).+ context: Context,/// The names of the files that went with it.files: Vec<String>,},@@ -254,6 +259,7 @@ struct Turn {pub struct Pending {pub text: String,pub image: bool,+ pub context: Context,/// The files attached to it (they go with it).pub files: Vec<attach::Attachment>,}@@ -308,6 +314,14 @@ pub struct AgentChat {documents: bool,/// Send a picture of the view with the next message.pub attach_view: bool,+ /// Send what is selected in the model with the next message.+ pub attach_selection: bool,+ /// How many things the current selection is by clicks, kept while the selection and the design+ /// stay as they are: (the selection, the design's address, the count).+ selected_count: Option<(Vec<solidcraft_engine::Sel>, usize, usize)>,+ /// What the user picked with Pick context for the next message, and how it reads.+ pub picked: Vec<solidcraft_engine::Sel>,+ pub picked_context: Context,auth: Vec<acp::AuthMethod>,auth_status: Option<String>,/// A message typed before the agent was ready: its text, whether the view goes with it, its@@ -846,6 +860,54 @@ const MAX_PENDING: usize = 20;/// incomplete.const INTERRUPT_NOTE: &str = "[The user interrupted your previous step.]";+/// How many things the selection is, counting what was clicked (the two halves of a rim are one).+pub fn selected_count(app: &mut SolveApp) -> usize {+ let doc = Arc::as_ptr(&app.session.doc) as usize;+ if let Some((selection, at, count)) = &app.agent_chat.selected_count+ && *at == doc+ && *selection == app.session.selection+ {+ return *count;+ }+ let count = context::selection_count(&app.session, &app.session.selection);+ app.agent_chat.selected_count = Some((app.session.selection.clone(), doc, count));+ count+}++/// Open the picker for the next message's context (what is already picked stays in it). Nothing+/// happens while another tool or dialog is open.+pub fn start_pick(app: &mut SolveApp) {+ if app.dialog.is_none() {+ app.dialog = Some(crate::dialogs::Dialog::chat_context(&app.agent_chat.picked));+ }+}++/// The picker's OK: what its inputs hold is the next message's context.+pub(crate) fn pick_done(app: &mut SolveApp, d: &crate::dialogs::Dialog) -> Result<(), String> {+ let mut picked: Vec<solidcraft_engine::Sel> = Vec::new();+ for sel in d.inputs.iter().flat_map(|i| i.items.iter()) {+ if !picked.contains(sel) {+ picked.push(sel.clone());+ }+ }+ app.agent_chat.picked_context = context::describe(&mut app.session, &picked);+ // The tray lists what was described; more than the limit is only counted.+ picked.truncate(context::MAX_ITEMS);+ app.agent_chat.picked = picked;+ Ok(())+}++/// Take one picked item (by its place in the tray) out of what the next message carries.+pub fn remove_picked(app: &mut SolveApp, at: usize) {+ let chat = &mut app.agent_chat;+ if at < chat.picked_context.items.len() {+ chat.picked_context.items.remove(at);+ if at < chat.picked.len() {+ chat.picked.remove(at);+ }+ }+}+/// Send what the user typed: now if the agent is ready, queued behind the running message if it/// is working, else once it is ready (starting it if needed).pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) {@@ -864,6 +926,15 @@ pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) {}let text = if text.trim().is_empty() { String::new() } else { text };let image = app.agent_chat.attach_view && app.agent_chat.images;+ // The selection is read now, when the user sends, not when a queued message finally goes.+ // What was picked goes first, then what is selected (without what was picked twice).+ let mut context = std::mem::take(&mut app.agent_chat.picked_context);+ app.agent_chat.picked.clear();+ if app.agent_chat.attach_selection {+ let mut selected = context::describe_selection(&mut app.session);+ selected.items.retain(|i| !context.items.contains(i));+ context.merge(selected);+ }if app.agent_chat.state() == State::Busy {let chat = &mut app.agent_chat;if chat.pending.len() >= MAX_PENDING {@@ -871,23 +942,23 @@ pub fn send(app: &mut SolveApp, ctx: &egui::Context, text: String) {chat.notice(tr("ui.agent_chat_queue_full"), false);} else {let files = std::mem::take(&mut chat.attachments);- chat.pending.push(Pending { text, image, files });+ chat.pending.push(Pending { text, image, context, files });}return;}let files = std::mem::take(&mut app.agent_chat.attachments);// Messages left waiting by Stop go first, in one prompt with this one.if !app.agent_chat.pending.is_empty() {- app.agent_chat.pending.push(Pending { text, image, files });+ app.agent_chat.pending.push(Pending { text, image, context, files });send_queue(app, ctx, false);return;}- submit(app, ctx, text, image, files, false);+ submit(app, ctx, text, image, context, files, false);}/// Put `text` in the conversation and send it with its files (`interrupted`: the agent is told it/// cut in on its previous step).-fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, files: Vec<attach::Attachment>, interrupted: bool) {+fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, context: Context, files: Vec<attach::Attachment>, interrupted: bool) {// Attached pictures show as thumbnails with the viewer, as the view's picture does; the other// files are listed by name.let pictures = files@@ -901,10 +972,13 @@ fn submit(app: &mut SolveApp, ctx: &egui::Context, text: String, image: bool, fitext: text.clone(),image,pictures,+ context: context.clone(),files: files.iter().filter(|f| !f.is_picture()).map(|f| f.name.clone()).collect(),});// The message's place in the conversation: its picture is kept there when it is taken.let at = app.agent_chat.items.len().checked_sub(1);+ // The agent gets the selection as text after the message; the conversation shows chips.+ let text = context::with_context(&text, &context);match app.agent_chat.state() {State::Ready => start_turn_with(app, text, image, at, files, interrupted.then_some(INTERRUPT_NOTE)),s => {@@ -929,9 +1003,11 @@ fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) {let all = std::mem::take(&mut chat.pending);let image = all.iter().any(|p| p.image);let mut files = Vec::new();+ let mut context = Context::default();let mut texts = Vec::new();for p in all {files.extend(p.files);+ context.merge(p.context);if !p.text.trim().is_empty() {texts.push(p.text);}@@ -944,7 +1020,7 @@ fn send_queue(app: &mut SolveApp, ctx: &egui::Context, interrupted: bool) {}let text = texts.join("\n\n");let text: String = text.chars().take(MAX_PROMPT).collect();- submit(app, ctx, text, image, files, interrupted);+ submit(app, ctx, text, image, context, files, interrupted);}/// Send now: stop the running step and send the queue as the next prompt once the agent has said@@ -976,6 +1052,8 @@ pub fn new_chat(app: &mut SolveApp) {chat.confirm_new = false;chat.items.clear();chat.gallery = None;+ chat.picked.clear();+ chat.picked_context = Context::default();chat.pending.clear();chat.attachments.clear();chat.loading.clear();@@ -1529,8 +1607,8 @@ pub fn set_mode(app: &mut SolveApp, mode: &str) {/// `ui.agent_chat` on the control channel (tests and screenshots): `enabled`, `command`, `open`,/// `side`, `minimized`, `width`, `refresh`, `connect`, `stop`, `attach` (a file's path, for the-/// next message), `remove_file` (index), `send`, `attach_view`, `permission` (an option id, or-/// `"cancel"`), `approve` (`true`/`false`, the oldest held+/// next message), `remove_file` (index), `send`, `attach_view`, `attach_selection`, `pick`,+/// `permission` (an option id, or `"cancel"`), `approve` (`true`/`false`, the oldest held/// request), `cancel` (Stop), `send_now` (steer: stop, then send the queue), `remove_pending` (index), `undo` (the newest message's changes); returns the panel's state.pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result<Value, String> {if let Some(e) = p.get("features").and_then(Value::as_bool) {@@ -1629,6 +1707,12 @@ pub fn control(app: &mut SolveApp, ctx: &egui::Context, p: &Value) -> Result<Valif let Some(a) = p.get("attach_view").and_then(Value::as_bool) {app.agent_chat.attach_view = a;}+ if let Some(a) = p.get("attach_selection").and_then(Value::as_bool) {+ app.agent_chat.attach_selection = a;+ }+ if p.get("pick").and_then(Value::as_bool) == Some(true) {+ start_pick(app);+ }if let Some(pick) = p.get("picker").and_then(Value::as_bool) {app.agent_chat.picking = Some(pick);}@@ -1686,7 +1770,7 @@ pub fn status(app: &SolveApp) -> Value {.items.iter().map(|i| match i {- Item::User { text, image, pictures, files } => json!({"user": text, "image": image, "pictures": pictures.len(), "files": files}),+ Item::User { text, image, pictures, context, files } => json!({"user": text, "image": image, "pictures": pictures.len(), "files": files, "context": context.items.iter().map(|i| json!({"label": i.label, "detail": i.detail})).collect::<Vec<_>>(), "context_omitted": context.omitted}),Item::Agent { thought, text } => json!({"agent": text, "thought": thought}),Item::Tool { id, title, kind, status, output } => {json!({"tool": id, "title": title, "kind": kind, "status": status.map(|s| format!("{s:?}")), "output": output})@@ -1736,7 +1820,8 @@ pub fn status(app: &SolveApp) -> Value {"toolsPort": c.tools_port,"pid": pid,"waiting": c.waiting(),- "pending": c.pending.iter().map(|p| json!({"text": p.text, "image": p.image, "files": p.files.iter().map(|f| f.name.clone()).collect::<Vec<_>>()})).collect::<Vec<_>>(),+ "picked": c.picked_context.items.iter().map(|i| json!({"label": i.label, "detail": i.detail})).collect::<Vec<_>>(),+ "pending": c.pending.iter().map(|p| json!({"text": p.text, "image": p.image, "context": p.context.total(), "files": p.files.iter().map(|f| f.name.clone()).collect::<Vec<_>>()})).collect::<Vec<_>>(),"attachments": c.attachments.iter().map(|f| f.name.clone()).collect::<Vec<_>>(),"loading": c.loading.iter().map(|f| f.name.clone()).collect::<Vec<_>>(),"stopped": c.stopped,diff --git a/crates/ui-egui/src/agent_chat/panel.rs b/crates/ui-egui/src/agent_chat/panel.rsindex 7d58ad5f89..b15974b653 100644--- a/crates/ui-egui/src/agent_chat/panel.rs+++ b/crates/ui-egui/src/agent_chat/panel.rs@@ -242,6 +242,120 @@ fn floating(app: &mut SolveApp, ui: &mut egui::Ui) {gallery_window(app, &ctx);}+/// The most chips one group shows before "+N more".+const MAX_CHIPS: usize = 6;+/// A chip's longest label (characters), and what its frame adds to the text's width.+const CHIP_CHARS: usize = 26;+const CHIP_PAD: f32 = 13.0;+/// What a chip's × adds.+const CHIP_CROSS: f32 = 14.0;++/// One thing in a group's rows: its heading, a chip for an item, or the "+N more" note.+#[cfg(not(target_arch = "wasm32"))]+enum ChipPart<'a> {+ Heading(String),+ /// An item and its place among all of the context's items.+ Chip(usize, &'a context::Entry),+ More(String),+}++/// What was selected when a message was sent, grouped (elements, features, bodies) with a count+/// each and a chip per item; hovering a chip tells what is known about it. The rows are filled by+/// hand: egui wraps plain widgets, not framed ones, and one row wider than the chat would widen+/// the whole panel.+#[cfg(not(target_arch = "wasm32"))]+fn context_chips(ui: &mut egui::Ui, context: &Context, removable: bool) -> Option<usize> {+ let mut removed = None;+ if context.is_empty() {+ return removed;+ }+ let t = Tokens::get();+ let font = egui::FontId::proportional(t.font_small);+ let (avail, gap) = (ui.available_width(), ui.spacing().item_spacing.x);+ let text_width = |ui: &egui::Ui, text: &str| ui.painter().layout_no_wrap(text.to_string(), font.clone(), t.text).size().x;+ let more = |n: usize| trf("ui.agent_chat_ctx_more", &[("n", &n.to_string())]);+ for kind in context::Kind::ALL {+ let items: Vec<(usize, &context::Entry)> = context.items.iter().enumerate().filter(|(_, i)| i.kind == kind).collect();+ if items.is_empty() {+ continue;+ }+ let mut parts = vec![ChipPart::Heading(format!("{} {}", tr(kind.heading()), items.len()))];+ parts.extend(items.iter().take(MAX_CHIPS).map(|(n, i)| ChipPart::Chip(*n, i)));+ if items.len() > MAX_CHIPS {+ parts.push(ChipPart::More(more(items.len() - MAX_CHIPS)));+ }+ let widths: Vec<f32> = parts+ .iter()+ .map(|p| match p {+ ChipPart::Heading(s) | ChipPart::More(s) => text_width(ui, s),+ ChipPart::Chip(_, i) => text_width(ui, &shorten(&i.label, CHIP_CHARS)) + CHIP_PAD + if removable { CHIP_CROSS } else { 0.0 },+ })+ .collect();+ let mut rows: Vec<Vec<usize>> = vec![Vec::new()];+ let mut used = 0.0_f32;+ for (n, w) in widths.iter().enumerate() {+ let fits = used + if used > 0.0 { gap } else { 0.0 } + w <= avail;+ if !fits && used > 0.0 {+ rows.push(Vec::new());+ used = 0.0;+ }+ used += if used > 0.0 { gap } else { 0.0 } + w;+ if let Some(row) = rows.last_mut() {+ row.push(n);+ }+ }+ for row in rows {+ ui.horizontal(|ui| {+ for n in row {+ match &parts[n] {+ ChipPart::Heading(s) | ChipPart::More(s) => {+ ui.label(RichText::new(s).color(t.text_dim).size(t.font_small));+ }+ ChipPart::Chip(place, item) => {+ let chip = egui::Frame::NONE+ .stroke(Stroke::new(1.0, t.text_dim.gamma_multiply(0.5)))+ .corner_radius(8.0)+ .inner_margin(egui::Margin::symmetric(5, 1))+ .show(ui, |ui| {+ ui.spacing_mut().item_spacing.x = 3.0;+ ui.horizontal(|ui| {+ let label = ui.add(+ egui::Label::new(RichText::new(shorten(&item.label, CHIP_CHARS)).color(t.text).size(t.font_small))+ .wrap_mode(egui::TextWrapMode::Extend),+ );+ if removable {+ let cross = ui_kit::button(ui, "×", ui_kit::Button::Small);+ crate::scenario::publish_handle(&format!("agent_chat:picked_remove:{place}"), cross.rect.center());+ if cross.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {+ removed = Some(*place);+ }+ }+ label+ })+ .inner+ })+ .response;+ if !item.detail.is_empty() {+ chip.on_hover_text(&item.detail);+ }+ }+ }+ }+ });+ }+ }+ if context.omitted > 0 {+ ui.label(RichText::new(more(context.omitted)).color(t.text_dim).size(t.font_small));+ }+ removed+}++/// `s` cut to `max` characters, with an ellipsis.+#[cfg(not(target_arch = "wasm32"))]+fn shorten(s: &str, max: usize) -> String {+ if s.chars().count() <= max { s.to_string() } else { format!("{}…", s.chars().take(max.saturating_sub(1)).collect::<String>()) }+}+/// The pictures of a message as small thumbnails in a row. Hovering one shows it bigger for as long/// as the pointer stays; a click returns its place in the row, to open the viewer there.#[cfg(not(target_arch = "wasm32"))]@@ -728,12 +842,18 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {} else {(false, false)};- let (mut send_clicked, mut stop_clicked, mut enter) = (false, false, false);+ let (mut send_clicked, mut stop_clicked, mut enter, mut pick_clicked) = (false, false, false, false);+ let mut remove_picked_at = None;let frame = Container::new(ui.ctx(), Surface::Viewport).edge_frame(egui::Color32::TRANSPARENT);let composer = Container::new(ui.ctx(), Surface::Viewport).edge(Id::new("sc_agent_chat_composer"), Edge::Bottom);composer.resizable(false).show_separator_line(false).frame(frame).show(ui, |ui| {ui_kit::assistant_composer_footer(ui, |ui| {ui_kit::assistant_composer(ui, focused, |ui| {+ // What Pick context chose for this message, each item with an ×.+ if !app.agent_chat.picked_context.is_empty() {+ let tray = app.agent_chat.picked_context.clone();+ remove_picked_at = context_chips(ui, &tray, true);+ }// The files for the next message (#1744), as chips of their own.attachment_chips(app, ui);// Ctrl/Cmd+V: files and pictures on the clipboard attach; text goes to the box below.@@ -840,6 +960,22 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {.on_hover_text(tr("ui.agent_chat_attach_view_tip")).on_disabled_hover_text(tr("ui.agent_chat_no_images"));crate::scenario::publish_handle("agent_chat:attach", attach.rect.center());+ // What is selected in the model goes with the message: text for the agent,+ // chips in the conversation.+ let selected = selected_count(app);+ let label = if selected > 0 {+ format!("{} ({selected})", tr("ui.agent_chat_attach_selection"))+ } else {+ tr("ui.agent_chat_attach_selection").to_string()+ };+ let pick = ui_kit::checkbox(ui, &label, &mut app.agent_chat.attach_selection)+ .on_hover_text(tr("ui.agent_chat_attach_selection_tip"));+ crate::scenario::publish_handle("agent_chat:attach_selection", pick.rect.center());+ // Choose faces, edges, features and bodies on purpose, then OK.+ let picker = ui_kit::button(ui, tr("ui.agent_chat_pick_context"), ui_kit::Button::Enabled(app.dialog.is_none()))+ .on_hover_text(tr("ui.agent_chat_pick_context_tip"));+ crate::scenario::publish_handle("agent_chat:pick_context", picker.rect.center());+ pick_clicked = picker.clicked();if let Some(turn) = &app.agent_chat.turn {let count = trf("ui.agent_chat_changes_of",@@ -852,6 +988,12 @@ fn desktop_body(app: &mut SolveApp, ui: &mut egui::Ui) {});});});+ if let Some(at) = remove_picked_at {+ remove_picked(app, at);+ }+ if pick_clicked {+ start_pick(app);+ }egui::ScrollArea::vertical().id_salt("sc_agent_chat_scroll").max_height(ui.available_height())@@ -1144,7 +1286,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {let current_doc = app.session.doc.clone();for (n, item) in app.agent_chat.items.iter().enumerate() {match item {- Item::User { text, image, pictures, files } => {+ Item::User { text, image, pictures, context, files } => {ui_kit::assistant_bubble(ui, |ui| {if !text.is_empty() {ui.add(egui::Label::new(RichText::new(text).color(t.text)).selectable(true).wrap());@@ -1157,6 +1299,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {// Taken when the agent starts on the message: nothing to show yet.ui.label(RichText::new(tr("ui.agent_chat_view_attached")).color(t.text_dim).size(t.font_small));}+ context_chips(ui, context, false);files_line(ui, files.iter().map(String::as_str));});}@@ -1340,6 +1483,7 @@ fn conversation(app: &mut SolveApp, ui: &mut egui::Ui) {if p.image {ui.label(RichText::new(tr("ui.agent_chat_view_attached")).color(t.text_dim).size(crate::theme::Tokens::get().font_small));}+ context_chips(ui, &p.context, false);files_line(ui, p.files.iter().map(|f| f.name.as_str()));}}diff --git a/crates/ui-egui/src/agent_chat/tests.rs b/crates/ui-egui/src/agent_chat/tests.rsindex 04c215735b..86d96c62d6 100644--- a/crates/ui-egui/src/agent_chat/tests.rs+++ b/crates/ui-egui/src/agent_chat/tests.rs@@ -39,7 +39,7 @@ fn a_sign_in_request_keeps_the_question_for_after_the_login() {#[test]fn a_plan_update_replaces_the_turns_plan() {let mut c = chat();- c.push(Item::User { text: "go".into(), image: false, pictures: Vec::new(), files: Vec::new() });+ c.push(Item::User { text: "go".into(), image: false, pictures: Vec::new(), files: Vec::new(), context: Context::default() });c.on_event(Event::Plan(vec![("a".into(), "pending".into())]));c.on_event(Event::Text { thought: false, text: "working".into() });c.on_event(Event::Plan(vec![("a".into(), "completed".into())]));@@ -1413,6 +1413,122 @@ fn an_agents_markdown_is_drawn_as_blocks() {h.frames(3);}+// ---- Attach selection (#2286) ----++/// A 40 x 30 x 20 block, its first face and first edge as the selection would hold them, its body+/// and its feature.+fn box_selection(app: &mut SolveApp) -> Vec<solidcraft_engine::Sel> {+ use solidcraft_engine::Sel;+ app.run("solid.box", json!({"length": 40, "width": 30, "height": 20})).expect("a box");+ let face = app.session.execute("model.faces", &json!({"body": "Body1"})).expect("faces")["faces"][0].clone();+ let edge = app.session.execute("model.edges", &json!({"body": "Body1"})).expect("edges")["edges"][0].clone();+ let at = |v: &Value| solidcraft_engine::geom::Vec3::new(v[0].as_f64().unwrap_or(0.0), v[1].as_f64().unwrap_or(0.0), v[2].as_f64().unwrap_or(0.0));+ vec![+ Sel::Face { body: "Body1".into(), index: face["index"].as_u64().unwrap_or(0) as usize, point: at(&face["point"]) },+ Sel::Edge { body: "Body1".into(), index: edge["index"].as_u64().unwrap_or(0) as usize, point: at(&edge["mid"]) },+ Sel::Feature { id: app.session.doc.features.first().map(|f| f.id).expect("a feature") },+ Sel::Body { name: "Body1".into() },+ ]+}++/// With Attach selection on, the message goes with what is selected: the agent gets it as text+/// after the message, the conversation shows the message as typed with the items as chips.+#[test]+fn an_attached_selection_goes_as_text_for_the_agent_and_as_chips_in_the_conversation() {+ let (mut app, script, ctx) = app_with_script();+ app.session.selection = box_selection(&mut app);+ // Off: the message is just the message.+ send(&mut app, &ctx, "plain".into());+ assert_eq!(script.calls(), ["prompt: plain"]);+ ended(&script, "");+ poll(&mut app, &ctx);++ app.agent_chat.attach_selection = true;+ send(&mut app, &ctx, "round this".into());+ let prompt = script.calls().pop().expect("a prompt");+ assert!(prompt.starts_with("prompt: round this\n\n[Selected in SolidCraft"), "{prompt}");+ for want in ["Elements:", "- Flat face ", "planar", "area ", "- Edge ", "length ", "name ", "Features:", "feature id", "Bodies:", "- Body1"] {+ assert!(prompt.contains(want), "{want:?} missing from {prompt}");+ }+ let Some(Item::User { text, context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") };+ assert_eq!(text, "round this", "the conversation shows what was typed");+ assert_eq!(context.items.len(), 4);+ let kinds: Vec<_> = context.items.iter().map(|i| i.kind).collect();+ assert_eq!(kinds, [context::Kind::Element, context::Kind::Element, context::Kind::Feature, context::Kind::Body]);+ // Nothing selected: nothing is added, and the box stays ticked.+ ended(&script, "");+ poll(&mut app, &ctx);+ app.session.selection.clear();+ send(&mut app, &ctx, "nothing".into());+ assert_eq!(script.calls().pop().as_deref(), Some("prompt: nothing"));+}++/// A queued message keeps the selection of the moment it was typed; queued messages go as one+/// prompt with all their items.+#[test]+fn queued_messages_keep_the_selection_they_were_typed_with() {+ use solidcraft_engine::Sel;+ let (mut app, script, ctx) = app_with_script();+ app.agent_chat.attach_selection = true;+ send(&mut app, &ctx, "first".into());+ app.session.selection = vec![Sel::Body { name: "Alpha".into() }];+ send(&mut app, &ctx, "second".into());+ app.session.selection = vec![Sel::Body { name: "Beta".into() }];+ send(&mut app, &ctx, "third".into());+ assert_eq!(app.agent_chat.pending.iter().map(|p| p.context.total()).collect::<Vec<_>>(), [1, 1]);+ ended(&script, "");+ poll(&mut app, &ctx);+ let prompt = script.calls().pop().expect("the queue went");+ assert!(prompt.starts_with("prompt: second\n\nthird\n\n[Selected"), "{prompt}");+ assert!(prompt.contains("- Alpha") && prompt.contains("- Beta"), "{prompt}");+ let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") };+ assert_eq!(context.items.iter().map(|i| i.label.as_str()).collect::<Vec<_>>(), ["Alpha", "Beta"]);+}++/// A large selection is capped and says how much is left out; nothing in it can break the prompt.+#[test]+fn a_huge_selection_is_counted_not_dropped_silently() {+ use solidcraft_engine::Sel;+ let mut session = solidcraft_engine::Session::default();+ let selection: Vec<Sel> = (0..100).map(|i| Sel::Body { name: format!("Body{i}") }).collect();+ let context = context::describe(&mut session, &selection);+ assert_eq!((context.items.len(), context.omitted, context.total()), (context::MAX_ITEMS, 100 - context::MAX_ITEMS, 100));+ assert!(context.prompt_block().contains("and 36 more, not listed"));+ // Two such messages together stay capped.+ let mut both = context.clone();+ both.merge(context);+ assert_eq!((both.items.len(), both.total()), (context::MAX_ITEMS, 200));+ // Unknown bodies, faces and features are described by what is known, without panicking.+ let odd = [+ Sel::Face { body: "Nope".into(), index: usize::MAX, point: solidcraft_engine::geom::Vec3::new(f64::NAN, f64::INFINITY, 0.0) },+ Sel::Edge { body: "Nope".into(), index: 7, point: solidcraft_engine::geom::Vec3::new(0.0, 0.0, 0.0) },+ Sel::Feature { id: u64::MAX },+ Sel::Plane { name: "XY".into() },+ Sel::SketchCurve { id: "c1".into() },+ ];+ let described = context::describe(&mut session, &odd);+ assert_eq!(described.items.len(), 5);+ assert!(described.prompt_block().contains("Other:"));+}++/// The checkbox shows the number selected, and the chips of a sent message are drawn grouped.+#[test]+fn the_selection_checkbox_and_the_chips_are_drawn() {+ let mut h = crate::scenario::Harness::new();+ h.call("ui.agent_chat", json!({"open": true}));+ h.frames(3);+ assert!(h.widget("Attach selection").is_some(), "the checkbox is there, with nothing selected");+ h.app.session.selection = box_selection(&mut h.app);+ h.frames(3);+ assert!(h.widget("Attach selection (4)").is_some(), "it counts what is selected");+ let context = context::describe_selection(&mut h.app.session);+ h.app.agent_chat.items.push(Item::User { text: "look".into(), image: false, pictures: Vec::new(), context, files: Vec::new() });+ h.frames(3);+ for heading in ["Elements 2", "Features 1", "Bodies 1"] {+ assert!(h.widget(heading).is_some(), "{heading} is drawn");+ }+}+#[test]fn assistant_marks_follow_chat_login_turns_and_approvals() {use AssistantMark::*;@@ -1501,7 +1617,13 @@ fn test_png(colour: [u8; 4], width: u32) -> Vec<u8> {fn a_messages_pictures_open_in_a_viewer() {let mut h = crate::scenario::Harness::new();h.call("ui.agent_chat", json!({"open": true}));- h.app.agent_chat.items.push(Item::User { text: "waiting".into(), image: true, pictures: Vec::new(), files: Vec::new() });+ h.app.agent_chat.items.push(Item::User {+ text: "waiting".into(),+ image: true,+ pictures: Vec::new(),+ files: Vec::new(),+ context: Context::default(),+ });h.frames(3);let [x, y] = h.widget("View attached").expect("the plain caption is drawn");h.call("ui.click", json!({"x": x, "y": y}));@@ -1511,7 +1633,7 @@ fn a_messages_pictures_open_in_a_viewer() {h.app.agent_chat.items.clear();let pictures = vec![Picture::new(test_png([200, 30, 30, 255], 8), "first view"), Picture::new(test_png([30, 30, 200, 255], 16), "")];let ours = pictures.clone();- h.app.agent_chat.items.push(Item::User { text: "look".into(), image: true, pictures, files: Vec::new() });+ h.app.agent_chat.items.push(Item::User { text: "look".into(), image: true, pictures, files: Vec::new(), context: Context::default() });h.frames(2);// Decoded in the background: let both finish before looking for thumbnails.for picture in &ours {@@ -1555,10 +1677,16 @@ fn a_messages_pictures_open_in_a_viewer() {#[test]fn the_picture_goes_to_the_message_it_was_taken_for() {let mut chat = AgentChat::default();- chat.push(Item::User { text: "no picture".into(), image: false, pictures: Vec::new(), files: Vec::new() });- chat.push(Item::User { text: "first".into(), image: true, pictures: vec![Picture::new(vec![1], "")], files: Vec::new() });- chat.push(Item::User { text: "second".into(), image: true, pictures: Vec::new(), files: Vec::new() });- chat.push(Item::User { text: "third".into(), image: true, pictures: Vec::new(), files: Vec::new() });+ chat.push(Item::User { text: "no picture".into(), image: false, pictures: Vec::new(), files: Vec::new(), context: Context::default() });+ chat.push(Item::User {+ text: "first".into(),+ image: true,+ pictures: vec![Picture::new(vec![1], "")],+ files: Vec::new(),+ context: Context::default(),+ });+ chat.push(Item::User { text: "second".into(), image: true, pictures: Vec::new(), files: Vec::new(), context: Context::default() });+ chat.push(Item::User { text: "third".into(), image: true, pictures: Vec::new(), files: Vec::new(), context: Context::default() });let sizes = |chat: &AgentChat| -> Vec<usize> {chat.items.iter()@@ -1592,7 +1720,7 @@ fn a_message_sent_again_after_sign_in_stays_the_message_it_was() {let (mut app, script, ctx) = app_with_script();app.agent_chat.images = true;// An older message that wanted a picture and has none.- app.agent_chat.push(Item::User { text: "older".into(), image: true, pictures: Vec::new(), files: Vec::new() });+ app.agent_chat.push(Item::User { text: "older".into(), image: true, pictures: Vec::new(), files: Vec::new(), context: Context::default() });app.agent_chat.attach_view = true;send(&mut app, &ctx, "the new one".into());let place = app.agent_chat.items.len() - 1;@@ -1623,6 +1751,7 @@ fn the_viewer_opens_in_the_popped_out_window() {text: "look".into(),image: true,pictures: vec![Picture::new(test_png([200, 30, 30, 255], 8), "first view")],+ context: Context::default(),files: Vec::new(),});h.frames(2);@@ -1636,6 +1765,163 @@ fn the_viewer_opens_in_the_popped_out_window() {assert!(crate::scenario::rect_of("agent_chat:gallery_picture").is_some(), "and it is drawn");}+// ---- Pick context (#2286) ----++/// Put `sels` into the open picker's inputs the way clicks would: each in the input that takes it.+fn pick_into_dialog(app: &mut SolveApp, sels: &[solidcraft_engine::Sel]) {+ use solidcraft_engine::Sel;+ let mut d = app.dialog.take().expect("the picker is open");+ for sel in sels {+ d.active = match sel {+ Sel::Face { .. } | Sel::Edge { .. } | Sel::Vertex { .. } => 0,+ Sel::Feature { .. } => 1,+ _ => 2,+ };+ d.pick(&app.session, sel.clone());+ }+ app.dialog = Some(d);+}++/// Pick context opens the picker with Elements, Features and Bodies; OK puts what was picked in the+/// tray above the message box, as chips with an ×; × takes one out; Cancel keeps what was there.+#[test]+fn the_picker_fills_a_tray_of_chips_that_can_be_trimmed() {+ let mut h = crate::scenario::Harness::new();+ h.call("ui.agent_chat", json!({"open": true}));+ let sels = box_selection(&mut h.app);+ h.frames(3);+ let [x, y] = h.widget("Pick context").expect("the button is there");+ h.call("ui.click", json!({"x": x, "y": y}));+ h.frames(3);+ assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(crate::dialogs::Kind::ChatContext)), "the picker opened");+ assert_eq!(h.app.dialog.as_ref().map(|d| d.inputs.iter().map(|i| i.label).collect::<Vec<_>>()), Some(vec!["Elements", "Features", "Bodies"]));+ pick_into_dialog(&mut h.app, &sels);+ h.frames(3);+ let [x, y] = h.widget("OK").expect("OK is offered");+ h.call("ui.click", json!({"x": x, "y": y}));+ h.frames(4);+ assert!(h.app.dialog.is_none(), "OK closed the picker");+ assert_eq!(h.app.agent_chat.picked.len(), 4);+ assert_eq!(h.app.agent_chat.picked_context.items.len(), 4);+ for heading in ["Elements 2", "Features 1", "Bodies 1"] {+ assert!(h.widget(heading).is_some(), "{heading} is drawn in the tray");+ }+ // × takes the body out: the tray and the picks stay in step.+ let cross = crate::scenario::handle_at("agent_chat:picked_remove:3").expect("every chip has an ×");+ h.call("ui.click", json!({"x": cross.x, "y": cross.y}));+ h.frames(4);+ assert_eq!(h.app.agent_chat.picked.len(), 3);+ assert!(h.app.agent_chat.picked_context.items.iter().all(|i| i.kind != context::Kind::Body));+ // Reopened, the picker holds what is in the tray; Cancel leaves it alone.+ start_pick(&mut h.app);+ assert_eq!(h.app.dialog.as_ref().map(|d| d.inputs.iter().map(|i| i.items.len()).collect::<Vec<_>>()), Some(vec![2, 1, 0]));+ pick_into_dialog(&mut h.app, &[solidcraft_engine::Sel::Body { name: "Body1".into() }]);+ crate::dialogs::cancel(&mut h.app);+ assert!(h.app.dialog.is_none());+ assert_eq!(h.app.agent_chat.picked.len(), 3, "Cancel keeps what was picked before");+ // The control channel opens it too and reports what is picked.+ let reply = h.call("ui.agent_chat", json!({"pick": true}));+ assert!(matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(crate::dialogs::Kind::ChatContext)));+ assert_eq!(reply["result"]["picked"].as_array().map(Vec::len), Some(3));+ crate::dialogs::cancel(&mut h.app);+ // While another dialog is open, the button does nothing.+ h.app.start("solid.box");+ let before = h.app.dialog.is_some();+ start_pick(&mut h.app);+ assert!(before && !matches!(h.app.dialog.as_ref().map(|d| &d.kind), Some(crate::dialogs::Kind::ChatContext)));+}++/// What was picked goes with the next message, once, together with an attached selection that does+/// not repeat it.+#[test]+fn the_picks_go_with_the_next_message_once() {+ let (mut app, script, ctx) = app_with_script();+ let sels = box_selection(&mut app);+ start_pick(&mut app);+ pick_into_dialog(&mut app, &sels[2..]); // the feature and the body+ let d = app.dialog.take().expect("the picker");+ pick_done(&mut app, &d).expect("OK");+ assert_eq!(app.agent_chat.picked_context.items.len(), 2);++ // The same body is also selected and Attach selection is on: it is listed once.+ app.session.selection = vec![sels[3].clone(), sels[0].clone()];+ app.agent_chat.attach_selection = true;+ send(&mut app, &ctx, "look at these".into());+ let prompt = script.calls().pop().expect("a prompt");+ assert!(prompt.starts_with("prompt: look at these\n\n[Selected in SolidCraft"), "{prompt}");+ assert!(prompt.contains("3 item(s)"), "two picked and one more selected: {prompt}");+ assert_eq!(prompt.matches("- Body1").count(), 1, "{prompt}");+ let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") };+ assert_eq!(context.items.len(), 3);+ assert!(app.agent_chat.picked.is_empty() && app.agent_chat.picked_context.is_empty(), "the tray is empty again");+ // The next message carries nothing of it.+ ended(&script, "");+ poll(&mut app, &ctx);+ app.agent_chat.attach_selection = false;+ send(&mut app, &ctx, "and now?".into());+ assert_eq!(script.calls().pop().as_deref(), Some("prompt: and now?"));+}++/// Two clicks on two rims are two things, not four edges (a click on a rim selects both halves for+/// the commands; the chat counts and describes what was clicked).+#[test]+fn a_rim_clicked_once_is_one_item_not_its_pieces() {+ use solidcraft_engine::Sel;+ let (mut app, script, ctx) = app_with_script();+ app.run("solid.cylinder", json!({"radius": 10, "height": 20})).expect("a cylinder");+ let (name, top, bottom, mid_top, mid_bottom) = {+ let st = app.session.world_state();+ let body = &st.bodies[0];+ let mesh = body.mesh();+ let rim_at = |z: f64| mesh.edges.iter().position(|e| e.len() > 3 && e.iter().all(|p| (p.z - z).abs() < 1e-6)).expect("a rim");+ let (top, bottom) = (rim_at(20.0), rim_at(0.0));+ (body.name.clone(), top, bottom, crate::viewport::polyline_mid(&mesh.edges[top]), crate::viewport::polyline_mid(&mesh.edges[bottom]))+ };+ crate::viewport::select(&mut app, Some(Sel::Edge { body: name.clone(), index: top, point: mid_top }), false, false);+ crate::viewport::select(&mut app, Some(Sel::Edge { body: name, index: bottom, point: mid_bottom }), true, false);+ assert_eq!(app.session.selection.len(), 4, "two clicks selected four halves");+ assert_eq!(selected_count(&mut app), 2, "the checkbox counts the two clicks");++ app.agent_chat.attach_selection = true;+ send(&mut app, &ctx, "these two rims".into());+ let prompt = script.calls().pop().expect("a prompt");+ assert!(prompt.contains("2 item(s)"), "{prompt}");+ assert_eq!(prompt.matches("(2 pieces)").count(), 2, "{prompt}");+ // A rim of radius 10 is about 62.8 mm round (the kernel's own figure), both halves together.+ assert!(prompt.contains("Edge 62.") && prompt.contains("mm (2 pieces)"), "{prompt}");+ let Some(Item::User { context, .. }) = app.agent_chat.items.last() else { panic!("a sent message") };+ assert_eq!(context.items.len(), 2);+ assert_eq!(context.total(), 2);+ // The detail still names the piece indices the tools take.+ assert!(context.items.iter().all(|i| i.detail.contains("indices [")), "{:?}", context.items);+}++/// The same for a surface the kernel splits at a seam: one click on the cylinder's wall is one item.+#[test]+fn a_split_wall_clicked_once_is_one_item() {+ use solidcraft_engine::Sel;+ let (mut app, script, ctx) = app_with_script();+ app.run("solid.cylinder", json!({"radius": 10, "height": 20})).expect("a cylinder");+ let wall = app.session.execute("model.faces", &json!({"body": "Body1"})).expect("faces")["faces"]+ .as_array()+ .and_then(|faces| faces.iter().find(|f| f["cylinder"]["radius"].is_number()).cloned())+ .expect("the wall");+ let at = &wall["point"];+ let point = solidcraft_engine::geom::Vec3::new(at[0].as_f64().unwrap_or(0.0), at[1].as_f64().unwrap_or(0.0), at[2].as_f64().unwrap_or(0.0));+ crate::viewport::select(+ &mut app,+ Some(Sel::Face { body: "Body1".into(), index: wall["index"].as_u64().unwrap_or(0) as usize, point }),+ false,+ false,+ );+ assert!(!app.session.selection.is_empty());+ assert_eq!(selected_count(&mut app), 1, "one click, however many patches it selected: {:?}", app.session.selection);+ app.agent_chat.attach_selection = true;+ send(&mut app, &ctx, "this wall".into());+ let prompt = script.calls().pop().expect("a prompt");+ assert!(prompt.contains("1 item(s)") && prompt.contains("Round face r10"), "{prompt}");+}+// ---- Attached pictures in the shared viewer ----/// A small picture encoded as `format`.@@ -1673,7 +1959,13 @@ fn attached_pictures_of_any_format_are_decoded_in_the_background() {for (format, width) in [(image::ImageFormat::Png, 8), (image::ImageFormat::Jpeg, 16), (image::ImageFormat::Gif, 12)] {let picture = Picture::new(encoded(format, width), format!("photo.{format:?}"));h.app.agent_chat.items.clear();- h.app.agent_chat.items.push(Item::User { text: "look".into(), image: false, pictures: vec![picture.clone()], files: Vec::new() });+ h.app.agent_chat.items.push(Item::User {+ text: "look".into(),+ image: false,+ pictures: vec![picture.clone()],+ files: Vec::new(),+ context: Context::default(),+ });h.frames(2);assert!(until_decoded(&mut h, &picture), "{format:?} was decoded");let texture = picture.decode.texture.get().and_then(|t| t.as_ref()).unwrap_or_else(|| panic!("{format:?} is a texture"));@@ -1683,7 +1975,13 @@ fn attached_pictures_of_any_format_are_decoded_in_the_background() {// Bytes that are no picture: the name where the thumbnail would be, and nothing breaks.let broken = Picture::new(b"not a picture at all".to_vec(), "fake.png");h.app.agent_chat.items.clear();- h.app.agent_chat.items.push(Item::User { text: "look".into(), image: false, pictures: vec![broken.clone()], files: Vec::new() });+ h.app.agent_chat.items.push(Item::User {+ text: "look".into(),+ image: false,+ pictures: vec![broken.clone()],+ files: Vec::new(),+ context: Context::default(),+ });assert!(until_decoded(&mut h, &broken));assert!(matches!(broken.decode.texture.get(), Some(None)), "it could not be read");assert!(h.widget("fake.png").is_some(), "its name stands in for the thumbnail");@@ -1695,7 +1993,7 @@ fn attached_pictures_of_any_format_are_decoded_in_the_background() {fn an_attached_picture_and_the_views_picture_share_the_viewer() {let mut chat = AgentChat::default();let attached = Picture::shared(Arc::new(encoded(image::ImageFormat::Jpeg, 16)), "photo.jpg", false);- chat.push(Item::User { text: "see".into(), image: true, pictures: vec![attached], files: Vec::new() });+ chat.push(Item::User { text: "see".into(), image: true, pictures: vec![attached], files: Vec::new(), context: Context::default() });chat.keep_picture(Some(0), encoded(image::ImageFormat::Png, 8));let Some(Item::User { pictures, .. }) = chat.items.last() else { panic!("a sent message") };assert_eq!(pictures.iter().map(|p| (p.note.as_str(), p.view)).collect::<Vec<_>>(), [("photo.jpg", false), ("", true)]);diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex a15604c219..780405a071 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -341,6 +341,9 @@ crate::dialog_descriptor::dialog_descriptors! {with: Vec<String>,fail: Vec<String>,},+ /// Pick what the agent chat's next message is about (#2286): elements, features and bodies.+ /// OK hands the picks to the chat (`agent_chat::pick_done`); nothing is run.+ ChatContext,/// Joints and components (`dialogs_assembly`).Assembly(crate::dialogs_assembly::Asm),/// Sheet metal (`dialogs_sheet`).@@ -632,6 +635,21 @@ impl Dialog {}}+ /// The picker for the agent chat's context, holding what is already picked.+ pub fn chat_context(picked: &[Sel]) -> Dialog {+ let mut inputs = vec![+ SelInput::new("Elements", FACES | EDGES | selection::VERTICES, true),+ SelInput::new("Features", selection::FEATURES, true),+ SelInput::new("Bodies", BODIES, true),+ ];+ for sel in picked {+ if let Some(input) = inputs.iter_mut().find(|i| fits(i.accept, sel)) {+ input.items.push(sel.clone());+ }+ }+ Dialog::new(Kind::ChatContext, inputs)+ }+pub fn for_command(app: &SolveApp, id: &str) -> Option<Dialog> {let s = &app.session;let has_bodies = !s.world_state().bodies.is_empty();@@ -1247,10 +1265,12 @@ impl Dialog {self.profile_selection_changed = true;}let measure = matches!(self.kind, Kind::Measure { .. });+ // The chat's picks stay what was clicked: a rim is one edge there, not its pieces.+ let one = measure || matches!(self.kind, Kind::ChatContext);let sel = if measure { crate::viewport::measurement_selection(s, &sel) } else { sel };let chain = matches!(self.kind, Kind::Fillet { chain: true, .. });let single =- if !measure && self.active_input().is_some_and(|i| i.multi) { crate::viewport::picked_selection(s, &sel) } else { vec![sel.clone()] };+ if !one && self.active_input().is_some_and(|i| i.multi) { crate::viewport::picked_selection(s, &sel) } else { vec![sel.clone()] };// Tangent chain: an edge brings the edges that continue it smoothly.let picked = if chain { fillet_edges(s, &sel, true) } else { single.clone() };// Extrude and revolve take profiles of one sketch.@@ -1767,6 +1787,7 @@ fn title(k: &Kind) -> &'static str {Kind::Align { .. } => "ALIGN",Kind::BoundaryFill { .. } => "BOUNDARY FILL",Kind::Remove => "REMOVE",+ Kind::ChatContext => "PICK CONTEXT",Kind::PathPattern { .. } => "PATTERN ON PATH",Kind::Split => "SPLIT BODY",Kind::Thread { .. } => "THREAD",@@ -2467,6 +2488,8 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {let has_ok = !matches!(d.kind, Kind::Sketch | Kind::Measure { .. });let valid = match &d.kind {Kind::Sketch => false,+ // Nothing picked is an answer too: OK empties the chat's tray.+ Kind::ChatContext => true,Kind::Material { editor, .. } if editor.editing() => false,Kind::SaveMesh(_) => crate::dialogs_save_mesh::ready(&d.inputs),Kind::SketchModify(crate::sketch_modify_ui::Mod::Corner { .. }) => {@@ -2648,6 +2671,7 @@ pub fn show(app: &mut SolveApp, ctx: &egui::Context) {// Edit Text applies its own way: its live changes and OK are one undo step.let run = match &mut d.kind {Kind::Text(k) => Some(crate::sketch_text::apply(app, k)),+ Kind::ChatContext => Some(crate::agent_chat::pick_done(app, &d)),_ => match begin_applying(app, &d) {// Computing: the dialog stays, saying so, until it is in.Begun::Later(job) => {@@ -3266,6 +3290,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S};let face_points = |i: usize| -> Vec<Value> { sels(d, i).face_points().into_iter().map(pt).collect() };let (cmd, params): (&str, Value) = match &d.kind {+ Kind::ChatContext => return Err("the chat takes these picks; nothing runs".into()),Kind::Extrude {distance,direction,diff --git a/crates/ui-egui/src/dialogs_dense.rs b/crates/ui-egui/src/dialogs_dense.rsindex bbd59a181f..e859873eda 100644--- a/crates/ui-egui/src/dialogs_dense.rs+++ b/crates/ui-egui/src/dialogs_dense.rs@@ -652,7 +652,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> booKind::Construct { t: Some(t), .. } => {form_row(ui, "Position (0 to 1)", |ui| enter |= field(ui, t));}- Kind::Split | Kind::ReplaceFace | Kind::Remove | Kind::Midplane | Kind::Construct { t: None, .. } => {}+ Kind::Split | Kind::ReplaceFace | Kind::Remove | Kind::Midplane | Kind::ChatContext | Kind::Construct { t: None, .. } => {}Kind::Rib { thickness, depth, flip, normal, .. } => {form_row(ui, "Direction", |ui| {let mut i = usize::from(*normal);diff --git a/crates/ui-egui/tests/assistant_render.rs b/crates/ui-egui/tests/assistant_render.rsindex 9902ecb464..746e8b8eb3 100644--- a/crates/ui-egui/tests/assistant_render.rs+++ b/crates/ui-egui/tests/assistant_render.rs@@ -30,6 +30,7 @@ fn assistant_transcript_tools_and_approvals_fit_in_both_themes() {text: "Make the plate 80 mm wide, soften its edges, and export a STEP file.".into(),image: false,pictures: vec![],+ context: Default::default(),files: vec!["plate-notes.txt".into()],},Item::Agent { thought: false, text: "I’ll update the width and check the selected edges before exporting.".into() },diff --git a/crates/ui-egui/tests/icon_audit.rs b/crates/ui-egui/tests/icon_audit.rsindex b47b29406f..af57592f9a 100644--- a/crates/ui-egui/tests/icon_audit.rs+++ b/crates/ui-egui/tests/icon_audit.rs@@ -101,7 +101,7 @@ fn assistant(h: &mut Harness, requested: &mut BTreeMap<String, bool>) {use solidcraft_ui_egui::agent_chat::{Item, backend::ToolStatus};h.call("ui.agent_chat", json!({"features":true,"open":true,"picker":false,"width":440}));h.app.agent_chat.items = vec![- Item::User { text: "Round the plate edges".into(), image: false, pictures: vec![], files: vec![] },+ Item::User { text: "Round the plate edges".into(), image: false, pictures: vec![], context: Default::default(), files: vec![] },Item::Tool {id: "audit".into(),title: "solid.fillet".into(),diff --git a/docs/agent-chat.md b/docs/agent-chat.mdindex df2955285d..9f01b9f425 100644--- a/docs/agent-chat.md+++ b/docs/agent-chat.md@@ -247,6 +247,22 @@ The agent reaches the open design only through SolidCraft's own tools (thewhile you do; click it to open the viewer (the message's pictures one at a time, with **‹** and**›** or the arrow keys, closed with Esc or a click outside). A long message scrolls inside itsbox, so **Send** and the buttons beside it stay in view.+- **Attach selection:** tick it to send what is selected in the model with your message, so the+ agent knows what "this edge" or "that feature" is. The box shows how many things are selected, counted as you clicked them (the two halves of a rim you clicked once are one).+ Faces and edges go with the names and numbers the agent's tools take and with their size and+ place (so they can be found again after an edit), features with their name and kind, bodies with+ their name. The agent gets them as text after your message; the conversation shows your message+ as typed with the things as chips below it, grouped (Elements, Features, Bodies) with a count;+ hover a chip for what the agent was told about it. At most 64 things go with one message; the+ rest are counted ("+N more"), not dropped silently. The selection is read when you send, also for+ a message that waits in the queue.+- **Pick context:** press it to choose what the message is about on purpose. A picker opens with+ three lists, **Elements** (faces, edges, vertices), **Features** (steps of the timeline) and+ **Bodies**; click things in the model, the timeline or the browser to put them in the list that+ is active (click a list to make it active; click a picked thing again to take it out). **OK**+ puts them as chips above the message box, each with a **×**; they go with the next message like+ an attached selection (and are shown the same way), and the box is empty again afterwards.+ **Cancel** keeps what was picked before.## Permissionsdiff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex df25c5ffbc..5b36ed7bda 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -242,7 +242,7 @@ labels; `prefs:measure_axis_distances` identifies the checkbox.| `ui.agent_cursor` | `show` (bool), `speed`: a number from 1 to 5 (times the normal speed) or `"instant"` (no animation: the command runs at once and the pointer jumps to where it acted), `follow_camera` (bool); all optional | the settings. While the cursor is shown, `engine.execute` first glides to the command's toolbar button and to each pick, then runs and replies; later requests wait their turn. It also follows the pointer input sent with `ui.move`, `ui.click`, `ui.drag` and `ui.scroll`, as each event reaches the app, and a press leaves a ripple. `"animate": false` on a call skips it || `engine.execute` → `view.layout` | `mode`: `floating` or `compact` | Apply and save the workspace layout without opening a dialog, changing the design, resetting the camera or cancelling its active tool. General preferences expose the same choice; `ui.prefs {"layout":"compact"}` also saves it. || `engine.execute` → `view.history_layout` | `width?`, `dock?`: `bottom`, `left`, `under_browser`, `collapsed?` | Resize/dock the history without opening a dialog or changing the design. Contents respond to measured width; browser-stacked history shares its width and splits height equally. One folded header gives the expanded card the rest; two folded headers stay at the top. |-| `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model`}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) |+| `ui.agent_chat` | `features?`, `toolbar_button?`, `permissions?` (`ask`, `edits`, `all`), `add_agent?` ({`name`, `kind`: `acp`, `api` or `anthropic` (`api` is OpenAI-compatible, `anthropic` Anthropic-compatible), `command` or `base_url` + `model`}; no keys), `add_dialog?` (`installed`, `custom`, `api`, `anthropic`, or `false` to close), `default_agent?`, `agent?` (the conversation's agent, by id), `mode?` (the agent's own mode), `model?` (one of its models), `open?`, `side?` (`left`, `right`), `minimized?`, `popped?` (in its own window), `width?`, `picker?`, `refresh?`, `connect?`, `stop?`, `attach?`: a file's path (a picture, a text file or a CAD file, for the next message; CAD files are imported at once), `remove_file?` (index of a file on the next message), `send?`: text (files alone make a message too), `attach_view?`, `attach_selection?`, `pick?` (true: open the context picker), `permission?`: an option id or `"cancel"` (the newest question of the agent's own), `approve?`: true, false or `"always"` (the oldest request held for Allow/Deny), `cancel?` (Stop: the queue stays), `send_now?` (stop the running step, then send the queued messages), `remove_pending?` (index), `new_chat?` (clear the chat, new session), `undo?` (the last message's changes) | the chat's state: `features`, `agents` (found and added), `currentAgent`, `state` (off, starting, ready, busy, auth, exited), `popped`, `window` (its place and size), `agent`, `modes`, `mode`, `models`, `model`, `authMethods`, `toolsPort`, `pid`, `waiting`, `turn`, `pending` (queued messages, with their `files`), `attachments` (the files on the next message, by name), `loading` (pictures still being read for it, by name), `stopped`, `detection` and the conversation (`items`). With `features` off only the settings apply. Desktop only; see [Agent chat](agent-chat.md) || `ui.resize` | `width`, `height` | || `app.quit` | `force?` (quit without asking about unsaved designs) | `quitting` (the window closes), `asking` (a "save changes?" prompt is open) |