Skip to content

Craft Anything: understand how any software works, and craft your own.

Rust

Keep agent answers within the conversation column (#719)

Carlos Douradof5d1f275a597
diff --git a/crates/ui-egui/src/chat.rs b/crates/ui-egui/src/chat.rs
index 99ba7a4e..b6c0a72a 100644
--- a/crates/ui-egui/src/chat.rs
+++ b/crates/ui-egui/src/chat.rs
@@ -551,27 +551,40 @@ pub fn rich_text(ui: &mut Ui, text: &str, with_glossary: bool) {
continue;
}
if let Some(h) = trimmed.strip_prefix("### ").or_else(|| trimmed.strip_prefix("## ")).or_else(|| trimmed.strip_prefix("# ")) {
- ui.label(RichText::new(h).font(theme::semibold(body.size + 2.0)));
+ ui.add(egui::Label::new(RichText::new(h).font(theme::semibold(body.size + 2.0))).wrap());
continue;
}
let (bullet, rest) = match trimmed.strip_prefix("- ").or_else(|| trimmed.strip_prefix("* ")) {
Some(r) => (true, r),
None => (false, trimmed),
};
- ui.horizontal_wrapped(|ui| {
- ui.spacing_mut().item_spacing.x = 0.0;
- if bullet {
- ui.label(RichText::new(" • ").color(t.accent));
- }
- inline(ui, rest, with_glossary, &body, &t);
- });
+ paragraph(ui, rest, bullet, with_glossary, &body, &t);
}
if in_code && !code.is_empty() {
code_block(ui, &code, &t);
}
}
-fn inline(ui: &mut Ui, text: &str, with_glossary: bool, body: &egui::FontId, t: &Tokens) {
+struct GlossarySpan {
+ start: usize,
+ end: usize,
+ word: String,
+ meaning: &'static str,
+}
+
+fn paragraph(ui: &mut Ui, text: &str, bullet: bool, with_glossary: bool, body: &egui::FontId, t: &Tokens) {
+ // Shape the whole paragraph together. Separate wrapping labels interleaved with glossary
+ // widgets can move the row's left edge backwards when a later run starts with a long link.
+ let mut job = egui::text::LayoutJob::default();
+ job.wrap.max_width = ui.available_width().max(1.0);
+ job.first_row_min_height = ui.spacing().interact_size.y;
+ let mut spans = Vec::new();
+ let mut at = 0;
+ if bullet {
+ let prefix = " • ";
+ job.append(prefix, 0.0, egui::TextFormat { font_id: body.clone(), color: t.accent, ..Default::default() });
+ at += prefix.chars().count();
+ }
// Split on ** and ` markers; alternate plain/bold and plain/code.
let mut bold = false;
for (bi, part) in text.split("**").enumerate() {
@@ -584,38 +597,77 @@ fn inline(ui: &mut Ui, text: &str, with_glossary: bool, body: &egui::FontId, t:
continue;
}
if code {
- ui.label(RichText::new(piece).font(theme::mono(body.size - 1.0)).color(t.accent_ink).background_color(t.code_bg));
+ job.append(
+ piece,
+ 0.0,
+ egui::TextFormat { font_id: theme::mono(body.size - 1.0), color: t.accent_ink, background: t.code_bg, ..Default::default() },
+ );
+ at += piece.chars().count();
continue;
}
let font = if bold { theme::semibold(body.size) } else { body.clone() };
+ let format = egui::TextFormat { font_id: font, color: t.text, ..Default::default() };
if with_glossary {
for (run, meaning) in glossary::segments(piece) {
- match meaning {
- Some(m) => {
- widgets::glossary_word(ui, &run, m, font.clone());
- }
- None => words(ui, &run, &font, t),
+ let end = at + run.chars().count();
+ job.append(&run, 0.0, format.clone());
+ if let Some(meaning) = meaning {
+ spans.push(GlossarySpan { start: at, end, word: run, meaning });
}
+ at = end;
}
} else {
- words(ui, piece, &font, t);
+ job.append(piece, 0.0, format);
+ at += piece.chars().count();
}
}
}
-}
-
-/// A run of text as one label: in a wrapping row egui starts it where the last one ended and
-/// breaks it between words, so a paragraph isn't one widget per word.
-fn words(ui: &mut Ui, text: &str, font: &egui::FontId, t: &Tokens) {
- if !text.is_empty() {
- ui.add(egui::Label::new(RichText::new(text).font(font.clone()).color(t.text)).wrap());
+ let galley = ui.fonts_mut(|fonts| fonts.layout_job(job));
+ let response = ui.add(egui::Label::new(galley.clone()));
+ if !ui.is_rect_visible(response.rect) {
+ return;
+ }
+ let hover = response.hover_pos();
+ let mut meaning = None;
+ for span in &spans {
+ let mut rows: Vec<egui::Rect> = Vec::new();
+ for index in span.start..span.end {
+ let from = galley.pos_from_cursor(egui::text::CCursor { index: egui::text::CharIndex(index), prefer_next_row: true });
+ let to = galley.pos_from_cursor(egui::text::CCursor { index: egui::text::CharIndex(index + 1), prefer_next_row: false });
+ if from.top() != to.top() {
+ continue;
+ }
+ let rect = egui::Rect::from_min_max(from.min, egui::pos2(to.left().max(from.left()), from.bottom()));
+ if let Some(last) = rows.last_mut().filter(|last| last.top() == rect.top()) {
+ *last = last.union(rect);
+ } else {
+ rows.push(rect);
+ }
+ }
+ for rect in rows {
+ let rect = rect.translate(response.rect.min.to_vec2());
+ let mut x = rect.left();
+ while x < rect.right() {
+ ui.painter().hline(x..=(x + 2.0).min(rect.right()), rect.bottom() - 1.0, egui::Stroke::new(1.0, t.accent));
+ x += 4.0;
+ }
+ if hover.is_some_and(|pos| rect.contains(pos)) {
+ meaning = Some(span);
+ }
+ }
+ }
+ if let Some(span) = meaning {
+ response.on_hover_ui(|ui| {
+ ui.label(RichText::new(&span.word).font(theme::semibold(theme::SMALL)));
+ ui.label(tr(span.meaning));
+ });
}
}
fn code_block(ui: &mut Ui, code: &str, t: &Tokens) {
egui::Frame::new().fill(t.code_bg).corner_radius(t.r()).inner_margin(Margin::same(10)).show(ui, |ui| {
ui.set_width(ui.available_width());
- ui.label(RichText::new(code.trim_end()).font(theme::mono(12.5)).color(t.text));
+ ui.add(egui::Label::new(RichText::new(code.trim_end()).font(theme::mono(12.5)).color(t.text)).wrap());
});
}
diff --git a/crates/ui-egui/tests/fixtures/message-width.md b/crates/ui-egui/tests/fixtures/message-width.md
new file mode 100644
index 00000000..1cc86a47
--- /dev/null
+++ b/crates/ui-egui/tests/fixtures/message-width.md
@@ -0,0 +1,5 @@
+Implementada extensão Manifest V3 em [extension/](file:///C:/Users/alice/MyDrive1/Documents/Craft%20Anything/demo1/extension/) com botão flutuante, menu de qualidades reais, rastreamento de rolagem/tela cheia e troca SPA.
+
+Criado host nativo Rust em [demo1_native_host.rs](file:///C:/Users/alice/MyDrive1/Documents/Craft%20Anything/demo1/app/src/bin/demo1_native_host.rs) e servidor IPC em [ipc.rs](file:///C:/Users/alice/MyDrive1/Documents/Craft%20Anything/demo1/app/src/ipc.rs) com auto-inicialização do app e multiplexação de áudio/vídeo via yt-dlp e ffmpeg em [engine.rs](file:///C:/Users/alice/MyDrive1/Documents/Craft%20Anything/demo1/app/src/engine.rs).
+
+Fluxo validado no Microsoft Edge com player HTML5, YouTube real (2160p a áudio) e streams confirmados por ffprobe; capturas salvas em [browser-integration/](file:///C:/Users/alice/MyDrive1/Documents/Craft%20Anything/demo1/checks/codex-review/browser-integration/).
diff --git a/crates/ui-egui/tests/paragraph.rs b/crates/ui-egui/tests/paragraph.rs
new file mode 100644
index 00000000..6a545a6e
--- /dev/null
+++ b/crates/ui-egui/tests/paragraph.rs
@@ -0,0 +1,32 @@
+//! Inline glossary hints survive shaping a whole paragraph, including Unicode before the term.
+use craft_anything_engine::{Mode, feed::FeedItem};
+use craft_anything_ui_egui::{CraftApp, demo};
+use egui_kittest::{Harness, kittest::Queryable};
+
+#[test]
+fn a_formatted_glossary_word_after_unicode_still_has_its_hover_hint() {
+ let mut h = Harness::builder().with_size(egui::vec2(1280.0, 820.0)).build_eframe(|cc| {
+ CraftApp::setup_context(&cc.egui_ctx);
+ let mut app = demo::app(demo::engine(Mode::Beginner, true));
+ demo::fill_project(&mut app);
+ app.state.feed = vec![FeedItem::Agent { text: "ação **IPC** e `source.rs`".into(), streaming: false }];
+ cc.egui_ctx.all_styles_mut(|style| style.interaction.tooltip_delay = 0.0);
+ app
+ });
+ h.run_steps(3);
+ let text = h
+ .output()
+ .shapes
+ .iter()
+ .find_map(|shape| match &shape.shape {
+ egui::Shape::Text(text) if text.galley.text().starts_with("ação IPC") => Some(text),
+ _ => None,
+ })
+ .expect("the formatted paragraph is painted");
+ let start = text.galley.pos_from_cursor(egui::text::CCursor { index: egui::text::CharIndex(5), prefer_next_row: true });
+ let end = text.galley.pos_from_cursor(egui::text::CCursor { index: egui::text::CharIndex(8), prefer_next_row: false });
+ let pointer = egui::pos2((start.left() + end.left()) / 2.0, start.center().y) + text.pos.to_vec2();
+ h.input_mut().events.push(egui::Event::PointerMoved(pointer));
+ h.run_steps(3);
+ h.get_by_label("Inter-process communication: how two parts of an app (or two apps) send messages to each other.");
+}
diff --git a/crates/ui-egui/tests/smoke.rs b/crates/ui-egui/tests/smoke.rs
index 0128657e..6c6b2f75 100644
--- a/crates/ui-egui/tests/smoke.rs
+++ b/crates/ui-egui/tests/smoke.rs
@@ -1995,6 +1995,69 @@ fn a_paragraph_is_drawn_as_one_piece_of_text() {
h.get_by_label("The snake moves faster now and the score is bigger.");
}
+#[test]
+fn long_agent_answers_do_not_push_the_conversation_under_the_sidebar() {
+ use craft_anything_ui_egui::state::FeedItem;
+ fn text_rects(shape: &egui::Shape, out: &mut Vec<egui::Rect>) {
+ match shape {
+ egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| text_rects(s, out)),
+ egui::Shape::Text(text) if text.galley.text().contains("file:///") || text.galley.text().contains("long_component_") => {
+ out.push(shape.visual_bounding_rect());
+ }
+ _ => {}
+ }
+ }
+ let long_path = format!("C:\\Example\\{}\\source.rs", "long_component_".repeat(40));
+ let long_link = format!("[source.rs](file:///C:/Example/{}/source.rs)", "nested_module/".repeat(40));
+ let replies = [
+ long_link,
+ format!("`{long_path}`"),
+ format!("```text\n{long_path}\n```"),
+ "servidor IPC [engine.rs](file:///C:/Users/alice/MyDrive1/Documents/Craft%20Anything/demo1/app/src/engine.rs).".to_string(),
+ include_str!("fixtures/message-width.md").to_string(),
+ ];
+ for size in [egui::vec2(1920.0, 1032.0), egui::vec2(1280.0, 820.0)] {
+ for in_chat in [false, true] {
+ for (case, reply) in replies.iter().enumerate() {
+ let reply = reply.clone();
+ let mut h = harness_sized(size, move || {
+ let mut a = demo::app(demo::engine(Mode::Beginner, true));
+ if in_chat {
+ demo::fill_ask(&mut a);
+ a.state.chat = vec![ChatItem::Assistant { text: "Before the long answer".into(), backend: None, streaming: false }];
+ } else {
+ demo::fill_project(&mut a);
+ a.state.feed = vec![FeedItem::Agent { text: "Before the long answer".into(), streaming: false }];
+ }
+ a
+ });
+ h.run_steps(3);
+ if in_chat {
+ h.state_mut().state.chat.push(ChatItem::Assistant { text: reply.clone(), backend: None, streaming: false });
+ h.state_mut().state.chat.push(ChatItem::Assistant { text: "After the long answer".into(), backend: None, streaming: false });
+ } else {
+ h.state_mut().state.feed.push(FeedItem::Agent { text: reply.clone(), streaming: false });
+ h.state_mut().state.feed.push(FeedItem::Agent { text: "After the long answer".into(), streaming: false });
+ }
+ h.run_steps(4);
+ let composer = h.get_by_label(if in_chat { "Ask a question" } else { "Ask for a change" }).rect();
+ let mut long = Vec::new();
+ for shape in &h.output().shapes {
+ text_rects(&shape.shape, &mut long);
+ }
+ assert!(!long.is_empty(), "the answer was not painted");
+ let after = h.get_by_label("After the long answer").rect();
+ assert!(
+ long.iter().all(|r| r.left() >= composer.left() - 2.0 && r.right() <= composer.right() + 2.0)
+ && after.left() >= composer.left() - 1.0
+ && after.right() <= composer.right() + 1.0,
+ "the answer displaced the conversation: long={long:?}, answer={after:?}, composer={composer:?}, size={size:?}, chat={in_chat}, case={case}"
+ );
+ }
+ }
+ }
+}
+
#[test]
fn make_says_who_builds_and_a_picked_builder_stays_with_the_project() {
use craft_anything_ai::{BackendConfig, BackendKind, rebuild::StandIns};
diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md
index f779231a..1e93b725 100644
--- a/docs/ROADMAP.md
+++ b/docs/ROADMAP.md
@@ -538,6 +538,9 @@ Owner: maintainers · Status: in progress
### R2.9 Everyday use: typing, projects, settings
Owner: maintainers · Status: in progress
Gaps found while using the app for real projects.
+- [x] Agent paragraphs with glossary terms and long file links wrap together without pushing
+ their card or later messages under the sidebar (#523); Project and Ask bounds checked at two sizes
+ — claimed: carl-dourado, branch hotfix/r2.9-523-message-width
- [x] A prompt brought back with Up keeps its pictures (their paths are absolute, so they don't
come back after the project is moved)
- [ ] Change a project's builder from its page (a tool, so the CLI and MCP can too) — in PR #245
diff --git a/docs/STATUS.md b/docs/STATUS.md
index ba7b39e4..28c78275 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -8,6 +8,7 @@ workspace clippy, layers, fmt and the secret scan of all history were clean. Chi
| Area | State | Verified by |
|---|---|---|
+| Conversation width | Agent paragraphs, inline code and fenced code stay within the message column, including glossary terms followed by long file links (#523) | UI regression checks painted text and subsequent answers against the composer bounds in Project and Ask at 1920 × 1032 and 1280 × 820; Unicode/formatted glossary hover check |
| Settings saved on exit | Pending app settings merge the session's latest AI table when its guard is available. A busy session defers non-AI edits in `config.pending.toml` without waiting for the tool; startup recovers them with the latest committed AI table | Isolated child-process regression exercises idle and busy exit saves, a late AI commit, startup recovery and pending non-AI edits; engine tests cover sidecar migrations and damaged/newer files. No live desktop shutdown was exercised |
| SQLite payload limits | Capped records retain column positions, disclose partial TEXT and BLOB values, omit incomplete BLOB hashes, and report partial coverage with read notes | Hand-built overflow-page regressions for five oversized records (including WITHOUT ROWID in declaration order) and two controls; table and index engine coverage and limitation regressions |
| SQLite added columns | Short records include missing trailing fields using literal column defaults, or NULL when absent; unsupported default expressions produce NULL with a row note. Stored fields and records longer than the schema retain their values. Defaults are filled before restoring rowid aliases | Nine hand-built parser regressions and an engine tool test cover added-column defaults, rewritten records and short records with a rowid alias, including a missing alias field |