BlueGit

ict rusty-teams

Files

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

proposal_card.rs

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