BlueGit

ict rusty-teams

Files

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

proposal_card.rs

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