BlueGit

ict rusty-teams

Files

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

proposal_card.rs

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