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