BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / proposal_card.rs

proposal_card.rs

proposal_card.rs 19.4 KiB Download Raw
1use std::rc::Rc;
2
3use chrono::{DateTime, Utc};
4use gpui_kit::assets::IconName;
5use gpui_kit::component::tooltip::Tooltip;
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use teams_core::{Draft, MentionInput, OBJECT_MARK};
10
11use crate::agent_api::{ProposalEntry, ProposalPicture, ProposalStatus, agent_label};
12use crate::render::{Block, layout_blocks, render_blocks};
13use crate::theme;
14use crate::views::attachment_tray::{Classification, OutgoingImage, classify, inline_image};
15use crate::views::composer::{Outgoing, ReplyPreview};
16use crate::views::widgets::icon;
17
18const CARD_MARGIN_X: f32 = 20.;
19const CARD_MARGIN_BOTTOM: f32 = 8.;
20const CARD_PADDING: f32 = 12.;
21const CARD_RADIUS: f32 = 10.;
22const CARD_GAP: f32 = 8.;
23const BUTTON_HEIGHT: f32 = 28.;
24const BUTTON_RADIUS: f32 = 7.;
25const BODY_LINE_HEIGHT: f32 = 20.;
26const BODY_MAX_LINES: f32 = 4.;
27const QUOTE_BAR_WIDTH: f32 = 2.;
28const BODY_PREVIEW_CHARACTERS: usize = 1200;
29const THUMBNAIL_HEIGHT: f32 = 48.;
30const THUMBNAIL_MAX_WIDTH: f32 = 120.;
31const THUMBNAIL_MIN_WIDTH: f32 = 16.;
32const THUMBNAIL_RADIUS: f32 = 6.;
33pub const PROPOSAL_CARD: &str = "shell/islands/main/proposal-card";
34pub const PROPOSAL_THUMBNAILS: &str = "shell/islands/main/proposal-card/thumbnails";
35pub const PROPOSAL_BUTTONS: &str = "shell/islands/main/proposal-card/buttons";
36
37pub type CardAction = Rc<dyn Fn(&mut Window, &mut App)>;
38
39#[derive(Clone)]
40pub struct CardActions {
41 pub send: CardAction,
42 pub edit: CardAction,
43 pub discard: CardAction,
44}
45
46fn open_session_available(session_id: &str, cx: &App) -> bool {
47 crate::agents::has_session(session_id, cx)
48}
49
50fn open_session(session_id: &str, _window: &mut Window, cx: &mut App) {
51 crate::agents::open_session(session_id, cx);
52}
53
54fn body_preview(text: &str) -> String {
55 let text = text.trim();
56 let cut: String = text.chars().take(BODY_PREVIEW_CHARACTERS).collect();
57 if cut.len() == text.len() {
58 return cut;
59 }
60 match cut.rfind('\n') {
61 Some(newline) => cut[..newline].to_owned(),
62 None => cut,
63 }
64}
65
66pub fn body_blocks(text: &str, mentions: &[mcp::ProposalMention]) -> Vec<Block> {
67 let inputs: Vec<MentionInput> = mentions
68 .iter()
69 .map(|mention| MentionInput::user(&mention.user_id, &mention.name))
70 .collect();
71 let preview = body_preview(text);
72 let (html, _) = teams_core::apply_mentions(&Draft::from_markdown(&preview).to_html(), &inputs);
73 layout_blocks(&teams_core::html_to_spans(&html))
74}
75
76fn inline_flags(pictures: &[ProposalPicture]) -> Vec<bool> {
77 let mut inline_used = 0;
78 pictures
79 .iter()
80 .map(|picture| {
81 let inline = matches!(
82 classify(&picture.name, &picture.bytes, inline_used),
83 Classification::Inline(_)
84 );
85 if inline {
86 inline_used += picture.bytes.len() as u64;
87 }
88 inline
89 })
90 .collect()
91}
92
93pub fn needs_upload(entry: &ProposalEntry) -> bool {
94 inline_flags(&entry.images).contains(&false)
95}
96
97pub fn picture_files(entry: &ProposalEntry) -> Vec<(String, Vec<u8>)> {
98 entry
99 .images
100 .iter()
101 .map(|picture| (picture.name.clone(), picture.bytes.to_vec()))
102 .collect()
103}
104
105/// Carries only the images the composer would send inline; `needs_upload` tells when others are left.
106pub fn outgoing_for(entry: &ProposalEntry, reply: Option<ReplyPreview>) -> Outgoing {
107 let flags = inline_flags(&entry.images);
108 let images: Vec<OutgoingImage> = entry
109 .images
110 .iter()
111 .zip(&flags)
112 .filter(|(_, inline)| **inline)
113 .filter_map(|(picture, _)| inline_image(picture.name.clone(), picture.bytes.to_vec()))
114 .map(OutgoingImage::Inline)
115 .collect();
116 let mut markdown = entry.proposal.text.trim().to_owned();
117 for _ in &images {
118 markdown.push_str("\n\n");
119 markdown.push(OBJECT_MARK);
120 }
121 Outgoing {
122 draft: Draft::from_markdown(&markdown),
123 subject: None,
124 mentions: entry
125 .proposal
126 .mentions
127 .iter()
128 .map(|mention| MentionInput::user(&mention.user_id, &mention.name))
129 .collect(),
130 reply,
131 edit: None,
132 images,
133 files: Vec::new(),
134 link_preview: None,
135 }
136}
137
138fn thumbnail_size(dimensions: Option<(u32, u32)>) -> (f32, f32) {
139 let width = dimensions
140 .filter(|(width, height)| *width > 0 && *height > 0)
141 .map_or(THUMBNAIL_HEIGHT, |(width, height)| {
142 THUMBNAIL_HEIGHT * width as f32 / height as f32
143 });
144 (
145 width
146 .clamp(THUMBNAIL_HEIGHT / 2., THUMBNAIL_MAX_WIDTH)
147 .round(),
148 THUMBNAIL_HEIGHT,
149 )
150}
151
152fn thumbnails(pictures: &[ProposalPicture]) -> Div {
153 h_flex()
154 .w_full()
155 .overflow_hidden()
156 .gap(px(CARD_GAP))
157 .debug_selector(|| PROPOSAL_THUMBNAILS.into())
158 .children(pictures.iter().map(|picture| {
159 let thumbnail = picture.thumbnail.as_ref();
160 let (width, height) = thumbnail_size(thumbnail.map(|thumbnail| thumbnail.dimensions));
161 div()
162 .w(px(width))
163 .h(px(height))
164 .min_w(px(THUMBNAIL_MIN_WIDTH))
165 .overflow_hidden()
166 .rounded(px(THUMBNAIL_RADIUS))
167 .bg(theme::surface_raised())
168 .children(thumbnail.map(|thumbnail| {
169 img(ImageSource::from(thumbnail.image.clone()))
170 .size_full()
171 .object_fit(ObjectFit::Cover)
172 }))
173 }))
174}
175
176pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
177 let minutes = (now - created_at).num_minutes().max(0);
178 match minutes {
179 0 => "just now".to_owned(),
180 1..=59 => format!("{minutes} min ago"),
181 60..=1439 => format!("{} h ago", minutes / 60),
182 _ => format!("{} d ago", minutes / 1440),
183 }
184}
185
186fn card_button(
187 id: &'static str,
188 label: &'static str,
189 background: Hsla,
190 color: Hsla,
191 action: CardAction,
192) -> Stateful<Div> {
193 div()
194 .id(id)
195 .h(px(BUTTON_HEIGHT))
196 .px(px(12.))
197 .flex()
198 .items_center()
199 .rounded(px(BUTTON_RADIUS))
200 .cursor_pointer()
201 .text_size(px(12.))
202 .font_weight(FontWeight::SEMIBOLD)
203 .bg(background)
204 .text_color(color)
205 .hover(|button| button.opacity(0.85))
206 .child(label)
207 .on_click(move |_, window, cx| action(window, cx))
208}
209
210fn header_text(entry: &ProposalEntry, now: DateTime<Utc>) -> (String, Hsla, Option<String>) {
211 let agent = agent_label(entry.proposal.agent.as_deref());
212 match &entry.status {
213 ProposalStatus::Pending => (
214 format!("{agent} proposes a reply"),
215 theme::accent_text(),
216 Some(format!(" - {}", age_label(entry.proposal.created_at, now))),
217 ),
218 ProposalStatus::Stale { answered_at } => (
219 format!(
220 "{agent}'s reply is outdated - you answered at {}",
221 answered_at.format("%H:%M")
222 ),
223 theme::text_muted(),
224 None,
225 ),
226 ProposalStatus::Failed { reason } => (
227 format!("Could not send - {reason}"),
228 theme::red_soft(),
229 None,
230 ),
231 }
232}
233
234pub fn render(
235 entry: &ProposalEntry,
236 quote: Option<String>,
237 actions: CardActions,
238 now: DateTime<Utc>,
239 cx: &App,
240) -> Div {
241 let stale = matches!(entry.status, ProposalStatus::Stale { .. });
242 let failed = matches!(entry.status, ProposalStatus::Failed { .. });
243 let (title, title_color, age) = header_text(entry, now);
244 let close = actions.discard.clone();
245 let header = h_flex()
246 .w_full()
247 .items_center()
248 .gap(px(4.))
249 .child(
250 h_flex()
251 .flex_1()
252 .min_w_0()
253 .items_baseline()
254 .overflow_hidden()
255 .text_size(px(12.))
256 .child(
257 div()
258 .truncate()
259 .font_weight(FontWeight::SEMIBOLD)
260 .text_color(title_color)
261 .child(title),
262 )
263 .children(
264 age.map(|age| div().flex_none().text_color(theme::text_faint()).child(age)),
265 ),
266 )
267 .child(
268 div()
269 .id("proposal-close")
270 .size(px(BUTTON_HEIGHT))
271 .flex_none()
272 .flex()
273 .items_center()
274 .justify_center()
275 .rounded(px(BUTTON_RADIUS))
276 .cursor_pointer()
277 .hover(|button| button.bg(theme::surface_raised()))
278 .child(icon(IconName::Close, 14., theme::text_muted()))
279 .on_click(move |_, window, cx| close(window, cx)),
280 );
281 let quote = quote.map(|quote| {
282 div()
283 .w_full()
284 .truncate()
285 .pl(px(8.))
286 .border_l(px(QUOTE_BAR_WIDTH))
287 .border_color(theme::border_strong())
288 .text_size(px(12.))
289 .text_color(theme::text_muted())
290 .child(quote)
291 });
292 let labels = entry.mention_labels.clone();
293 let body = div()
294 .id("proposal-text")
295 .w_full()
296 .max_h(px(BODY_LINE_HEIGHT * BODY_MAX_LINES))
297 .overflow_hidden()
298 .text_size(px(14.))
299 .line_height(px(BODY_LINE_HEIGHT))
300 .when(stale, |body| body.opacity(0.6))
301 .child(render_blocks(&entry.body, "proposal-body", false, cx))
302 .when(!labels.is_empty(), |body| {
303 body.tooltip(move |window, cx| {
304 Tooltip::new(format!("Mentions: {}", labels.join(", "))).build(window, cx)
305 })
306 });
307 let images = (!entry.images.is_empty()).then(|| thumbnails(&entry.images));
308 let session = entry
309 .proposal
310 .session_id
311 .clone()
312 .filter(|session_id| open_session_available(session_id, cx));
313 let buttons = h_flex()
314 .w_full()
315 .items_center()
316 .gap(px(8.))
317 .debug_selector(|| PROPOSAL_BUTTONS.into())
318 .when(!stale, |row| {
319 row.child(card_button(
320 "proposal-send",
321 if failed { "Retry" } else { "Send" },
322 theme::accent(),
323 theme::on_accent(),
324 actions.send.clone(),
325 ))
326 })
327 .child(card_button(
328 "proposal-edit",
329 "Edit",
330 theme::surface_raised(),
331 theme::text(),
332 actions.edit.clone(),
333 ))
334 .child(card_button(
335 "proposal-discard",
336 "Discard",
337 theme::surface_raised(),
338 theme::text(),
339 actions.discard.clone(),
340 ))
341 .children(session.map(|session_id| {
342 div()
343 .id("proposal-open-session")
344 .ml_auto()
345 .cursor_pointer()
346 .text_size(px(12.))
347 .text_color(theme::accent_text())
348 .child("Open session")
349 .on_click(move |_, window, cx| open_session(&session_id, window, cx))
350 }));
351 v_flex()
352 .flex_none()
353 .mx(px(CARD_MARGIN_X))
354 .mb(px(CARD_MARGIN_BOTTOM))
355 .p(px(CARD_PADDING))
356 .gap(px(CARD_GAP))
357 .rounded(px(CARD_RADIUS))
358 .bg(theme::row_hover())
359 .debug_selector(|| PROPOSAL_CARD.into())
360 .child(header)
361 .children(quote)
362 .child(body)
363 .children(images)
364 .child(buttons)
365}
366
367#[cfg(test)]
368pub fn sample_png(side: u32, padded_to: usize) -> Vec<u8> {
369 let mut bytes = Vec::new();
370 image::RgbaImage::new(side, side)
371 .write_to(
372 &mut std::io::Cursor::new(&mut bytes),
373 image::ImageFormat::Png,
374 )
375 .unwrap();
376 if bytes.len() < padded_to {
377 bytes.resize(padded_to, 0);
378 }
379 bytes
380}
381
382#[cfg(test)]
383pub fn sample_entry(text: &str, mentions: &[(&str, &str)], images: &[Vec<u8>]) -> ProposalEntry {
384 ProposalEntry {
385 body: std::sync::Arc::new(body_blocks(text, &[])),
386 mention_labels: Vec::new(),
387 proposal: mcp::Proposal {
388 id: "p1".to_owned(),
389 conversation_id: "c1".to_owned(),
390 reply_to_message_id: None,
391 text: text.to_owned(),
392 mentions: mentions
393 .iter()
394 .map(|(user_id, name)| mcp::ProposalMention {
395 user_id: (*user_id).to_owned(),
396 name: (*name).to_owned(),
397 })
398 .collect(),
399 images: Vec::new(),
400 agent: None,
401 session_id: None,
402 created_at: Utc::now(),
403 },
404 images: images
405 .iter()
406 .enumerate()
407 .map(|(index, bytes)| ProposalPicture {
408 name: format!("image-{index}.png"),
409 bytes: std::sync::Arc::new(bytes.clone()),
410 thumbnail: None,
411 })
412 .collect(),
413 status: crate::agent_api::ProposalStatus::Pending,
414 }
415}
416
417#[cfg(test)]
418mod tests {
419 use chrono::{Duration, Utc};
420 use teams_core::MentionInput;
421
422 use super::{
423 age_label, body_blocks, needs_upload, outgoing_for, picture_files, sample_entry,
424 sample_png, thumbnail_size,
425 };
426 use crate::render::Block;
427 use crate::views::attachment_tray::{AttachmentTray, INLINE_IMAGE_MAX_BYTES, OutgoingImage};
428
429 const TWO_MEGABYTES: usize = 2 * 1024 * 1024;
430
431 #[test]
432 fn age_labels_follow_the_elapsed_time() {
433 let now = Utc::now();
434 let label = |minutes: i64| age_label(now - Duration::minutes(minutes), now);
435 assert_eq!(label(0), "just now");
436 assert_eq!(label(1), "1 min ago");
437 assert_eq!(label(59), "59 min ago");
438 assert_eq!(label(120), "2 h ago");
439 assert_eq!(label(3000), "2 d ago");
440 assert_eq!(age_label(now + Duration::minutes(5), now), "just now");
441 }
442
443 #[test]
444 fn the_card_body_renders_markdown_like_a_sent_message() {
445 let blocks = body_blocks("- item\n- `code`", &[]);
446 let [Block::List { items, ordered, .. }] = blocks.as_slice() else {
447 panic!("{blocks:?}");
448 };
449 assert!(!ordered);
450 assert_eq!(items.len(), 2);
451 let Block::Paragraph(inline) = &items[1][0] else {
452 panic!("{items:?}");
453 };
454 assert_eq!(inline.text, "code");
455 assert!(inline.segments.iter().any(|segment| segment.style.code));
456 }
457
458 #[test]
459 fn long_bodies_are_cut_at_the_last_line_break() {
460 let text = format!("{}\n{}", "a".repeat(1000), "b".repeat(500));
461 assert_eq!(super::body_preview(&text), "a".repeat(1000));
462 assert_eq!(super::body_preview("short"), "short");
463 }
464
465 #[test]
466 fn long_bodies_are_cut_before_layout() {
467 let long = "word ".repeat(2000);
468 let blocks = body_blocks(&long, &[]);
469 let crate::render::Block::Paragraph(inline) = &blocks[0] else {
470 panic!("{blocks:?}");
471 };
472 assert!(inline.text.chars().count() <= super::BODY_PREVIEW_CHARACTERS);
473 }
474
475 #[test]
476 fn mentions_and_links_render_as_styled_segments() {
477 let blocks = body_blocks(
478 "**Hi** @Ada Example, see https://example.com/x",
479 &[mcp::ProposalMention {
480 user_id: "u1".to_owned(),
481 name: "Ada Example".to_owned(),
482 }],
483 );
484 let Block::Paragraph(inline) = &blocks[0] else {
485 panic!("{blocks:?}");
486 };
487 assert!(inline.segments.iter().any(|segment| segment.style.bold));
488 assert!(inline.segments.iter().any(|segment| segment.style.mention));
489 assert!(inline.segments.iter().any(|segment| segment.link.is_some()));
490 assert!(!inline.text.contains("**"));
491 }
492
493 #[test]
494 fn thumbnails_keep_the_height_and_clamp_the_width() {
495 assert_eq!(thumbnail_size(Some((100, 100))), (48., 48.));
496 assert_eq!(thumbnail_size(Some((1000, 100))), (120., 48.));
497 assert_eq!(thumbnail_size(Some((10, 100))), (24., 48.));
498 assert_eq!(thumbnail_size(None), (48., 48.));
499 }
500
501 #[test]
502 fn send_hands_images_and_mentions_to_the_outgoing_message() {
503 let entry = sample_entry(
504 "Thanks @Ada Example and @Bo",
505 &[("u1", "Ada Example"), ("u2", "Bo")],
506 &[sample_png(2, 0), sample_png(3, 0)],
507 );
508 assert!(!needs_upload(&entry));
509 let outgoing = outgoing_for(&entry, None);
510 assert_eq!(
511 outgoing.mentions,
512 [
513 MentionInput::user("u1", "Ada Example"),
514 MentionInput::user("u2", "Bo")
515 ]
516 );
517 assert_eq!(outgoing.images.len(), 2);
518 assert_eq!(outgoing.extras().images.len(), 2);
519 assert!(outgoing.html().starts_with("Thanks @Ada Example and @Bo"));
520 assert_eq!(
521 outgoing
522 .html()
523 .matches("<img src=\"../hostedContents/")
524 .count(),
525 2
526 );
527 assert_eq!(outgoing.text().trim(), "Thanks @Ada Example and @Bo");
528 }
529
530 #[test]
531 fn a_proposal_without_extras_stays_plain_text() {
532 let outgoing = outgoing_for(&sample_entry("hello", &[], &[]), None);
533 assert!(outgoing.mentions.is_empty());
534 assert!(outgoing.images.is_empty());
535 assert_eq!(outgoing.html(), "hello");
536 }
537
538 #[test]
539 fn images_over_the_inline_limits_are_left_for_upload() {
540 let big = || sample_png(2, TWO_MEGABYTES);
541 let entry = sample_entry("two big ones", &[], &[big(), big()]);
542 assert!(needs_upload(&entry));
543 let outgoing = outgoing_for(&entry, None);
544 assert!(outgoing.images.is_empty());
545 assert_eq!(picture_files(&entry).len(), 2);
546
547 let mixed = sample_entry("mixed", &[], &[sample_png(2, 0), big(), sample_png(3, 0)]);
548 assert!(needs_upload(&mixed));
549 assert_eq!(outgoing_for(&mixed, None).images.len(), 2);
550
551 let over_one = sample_entry(
552 "limit",
553 &[],
554 &[sample_png(2, INLINE_IMAGE_MAX_BYTES as usize + 1)],
555 );
556 assert!(needs_upload(&over_one));
557 let at_limit = sample_entry(
558 "limit",
559 &[],
560 &[sample_png(2, INLINE_IMAGE_MAX_BYTES as usize)],
561 );
562 assert!(!needs_upload(&at_limit));
563 }
564
565 #[test]
566 fn the_total_inline_budget_counts_across_images() {
567 let almost_one_megabyte = || sample_png(2, 1024 * 1024);
568 let entry = sample_entry(
569 "three",
570 &[],
571 &[
572 almost_one_megabyte(),
573 almost_one_megabyte(),
574 almost_one_megabyte(),
575 ],
576 );
577 assert!(needs_upload(&entry));
578 assert_eq!(outgoing_for(&entry, None).images.len(), 2);
579 }
580
581 #[test]
582 fn inline_images_go_back_into_the_tray_in_order() {
583 let entry = sample_entry("look", &[], &[sample_png(2, 0), sample_png(3, 0)]);
584 let outgoing = outgoing_for(&entry, None);
585 let mut tray = AttachmentTray::default();
586 let ids = tray.restore(&outgoing.images, &outgoing.files);
587 assert_eq!(ids.len(), 2);
588 let restored = tray.images_in(&ids);
589 assert_eq!(restored, outgoing.images);
590 assert!(matches!(restored[0], OutgoingImage::Inline(_)));
591 assert_eq!(
592 outgoing
593 .draft
594 .text()
595 .matches(teams_core::OBJECT_MARK)
596 .count(),
597 2
598 );
599 }
600}