BlueGit

ict rusty-teams

feat(composer): attach menu with recent and searchable cloud files like Teams

- Recent cloud files from Graph me/drive/recent, documents only, "Opened N days ago"
- Search cloud files through the Substrate file search
- a picked file is shared with the chat and attached by reference; removing it deletes nothing
- Upload from this device opens the file picker
- composer key handling skips side inputs (attach search, Copilot custom prompt)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-09 · 3 weeks ago

Hash
03526c4c8eb35da8108ec6ad96757c449f16ed64
Parent
ce2236f4
13 files changed +766 −23
crates/app/src/views/attachment_tray.rs +38 −2
@@ -9,7 +9,7 @@ use gpui_kit::prelude::FluentBuilder as _;
9 9 use gpui_kit::*;
10 10 use teams_core::{FileKind, FileReference, UploadedFile};
11 11
12 use super::attachments::file_badge;
12 use super::attachments::{file_badge, kind_description};
13 13 use super::widgets::icon;
14 14 use crate::format;
15 15 use crate::inline_image::{InlineFormat, image_dimensions, sniff_inline_format};
@@ -260,6 +260,28 @@ impl AttachmentTray {
260 260 self.next_id
261 261 }
262 262
263 /// A file already in the cloud goes out by reference; it was never uploaded, so removing it deletes nothing.
264 pub fn add_cloud_file(&mut self, name: String, size: u64, reference: FileReference) -> Option<u64> {
265 self.notice = None;
266 if self.items.len() >= MAX_ATTACHMENTS {
267 self.notice = Some(limit_notice(1));
268 return None;
269 }
270 let kind = ItemKind::File {
271 bytes: Arc::new(Vec::new()),
272 upload: UploadState::Done(DoneFile {
273 reference,
274 uploaded: None,
275 }),
276 sent_as_file: false,
277 };
278 Some(self.push(name, size, kind))
279 }
280
281 pub fn set_notice(&mut self, notice: String) {
282 self.notice = Some(notice);
283 }
284
263 285 /// Items beyond the limit are dropped; the ids returned belong to the first names.
264 286 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
265 287 self.notice = None;
@@ -652,7 +674,11 @@ pub struct ChipState {
652 674 }
653 675
654 676 pub fn chip_state(item: &TrayItem) -> ChipState {
655 let size = format::file_size_label(item.size);
677 let size = if item.size == 0 {
678 kind_description(FileKind::from_name(&item.name)).to_owned()
679 } else {
680 format::file_size_label(item.size)
681 };
656 682 let muted = |subtitle: String| ChipState {
657 683 subtitle,
658 684 tone: Tone::Muted,
@@ -1064,6 +1090,16 @@ mod tests {
1064 1090 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1065 1091 }
1066 1092
1093 #[test]
1094 fn a_cloud_file_is_ready_at_once_and_removing_it_deletes_nothing() {
1095 let mut tray = AttachmentTray::default();
1096 let id = tray.add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf")).unwrap();
1097 assert!(!tray.blocks_send());
1098 assert_eq!(tray.outgoing_files()[0].reference, reference("plan.pdf"));
1099 assert!(tray.retry(id).is_none());
1100 assert_eq!(tray.remove(id), None);
1101 }
1102
1067 1103 #[test]
1068 1104 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1069 1105 let (mut tray, id) = tray_with_file();
@@ -9,7 +9,7 @@ use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
9use gpui_kit::*;
10use teams_core::{FileKind, FileReference, UploadedFile};
10use teams_core::{FileKind, FileReference, UploadedFile};
11
11
12use super::attachments::file_badge;
12use super::attachments::{file_badge, kind_description};
13use super::widgets::icon;
13use super::widgets::icon;
14use crate::format;
14use crate::format;
15use crate::inline_image::{InlineFormat, image_dimensions, sniff_inline_format};
15use crate::inline_image::{InlineFormat, image_dimensions, sniff_inline_format};
@@ -260,6 +260,28 @@ impl AttachmentTray {
260 self.next_id
260 self.next_id
261 }
261 }
262
262
263 /// A file already in the cloud goes out by reference; it was never uploaded, so removing it deletes nothing.
264 pub fn add_cloud_file(&mut self, name: String, size: u64, reference: FileReference) -> Option<u64> {
265 self.notice = None;
266 if self.items.len() >= MAX_ATTACHMENTS {
267 self.notice = Some(limit_notice(1));
268 return None;
269 }
270 let kind = ItemKind::File {
271 bytes: Arc::new(Vec::new()),
272 upload: UploadState::Done(DoneFile {
273 reference,
274 uploaded: None,
275 }),
276 sent_as_file: false,
277 };
278 Some(self.push(name, size, kind))
279 }
280
281 pub fn set_notice(&mut self, notice: String) {
282 self.notice = Some(notice);
283 }
284
263 /// Items beyond the limit are dropped; the ids returned belong to the first names.
285 /// Items beyond the limit are dropped; the ids returned belong to the first names.
264 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
286 pub fn add_pending(&mut self, names: &[String]) -> Vec<u64> {
265 self.notice = None;
287 self.notice = None;
@@ -652,7 +674,11 @@ pub struct ChipState {
652}
674}
653
675
654pub fn chip_state(item: &TrayItem) -> ChipState {
676pub fn chip_state(item: &TrayItem) -> ChipState {
655 let size = format::file_size_label(item.size);
677 let size = if item.size == 0 {
678 kind_description(FileKind::from_name(&item.name)).to_owned()
679 } else {
680 format::file_size_label(item.size)
681 };
656 let muted = |subtitle: String| ChipState {
682 let muted = |subtitle: String| ChipState {
657 subtitle,
683 subtitle,
658 tone: Tone::Muted,
684 tone: Tone::Muted,
@@ -1064,6 +1090,16 @@ mod tests {
1064 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1090 assert!(matches!(tray.items()[2].kind, ItemKind::File { .. }));
1065 }
1091 }
1066
1092
1093 #[test]
1094 fn a_cloud_file_is_ready_at_once_and_removing_it_deletes_nothing() {
1095 let mut tray = AttachmentTray::default();
1096 let id = tray.add_cloud_file("plan.pdf".into(), 12, reference("plan.pdf")).unwrap();
1097 assert!(!tray.blocks_send());
1098 assert_eq!(tray.outgoing_files()[0].reference, reference("plan.pdf"));
1099 assert!(tray.retry(id).is_none());
1100 assert_eq!(tray.remove(id), None);
1101 }
1102
1067 #[test]
1103 #[test]
1068 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1104 fn a_failed_share_retries_only_the_share_and_keeps_the_upload() {
1069 let (mut tray, id) = tray_with_file();
1105 let (mut tray, id) = tray_with_file();
crates/app/src/views/attachments.rs +4 −0
@@ -157,6 +157,10 @@ fn kind_style(kind: FileKind) -> KindStyle {
157 157 }
158 158 }
159 159
160 pub fn kind_description(kind: FileKind) -> &'static str {
161 kind_style(kind).description
162 }
163
160 164 pub fn file_subtitle(card: &FileCard) -> String {
161 165 let description = kind_style(card.kind).description;
162 166 match card.size {
@@ -157,6 +157,10 @@ fn kind_style(kind: FileKind) -> KindStyle {
157 }
157 }
158}
158}
159
159
160pub fn kind_description(kind: FileKind) -> &'static str {
161 kind_style(kind).description
162}
163
160pub fn file_subtitle(card: &FileCard) -> String {
164pub fn file_subtitle(card: &FileCard) -> String {
161 let description = kind_style(card.kind).description;
165 let description = kind_style(card.kind).description;
162 match card.size {
166 match card.size {
crates/app/src/views/composer.rs +50 −19
@@ -31,6 +31,7 @@ use teams_core::{
31 31 };
32 32
33 33 pub(crate) mod delivery;
34 mod attach_menu;
34 35 mod drafts;
35 36 mod format_menus;
36 37 pub(crate) mod plus_menu;
@@ -260,6 +261,7 @@ pub struct Composer {
260 261 caret_text: String,
261 262 importance: store::MessageImportance,
262 263 rewrite: rewrite::RewritePanel,
264 attach_menu: attach_menu::AttachMenu,
263 265 delivery_menu: bool,
264 266 plus_menu: bool,
265 267 _subscriptions: [Subscription; 4],
@@ -533,6 +535,7 @@ impl Composer {
533 535 caret_text: String::new(),
534 536 importance: store::MessageImportance::Normal,
535 537 rewrite: rewrite::RewritePanel::default(),
538 attach_menu: attach_menu::AttachMenu::default(),
536 539 delivery_menu: false,
537 540 plus_menu: false,
538 541 _subscriptions: [subscription, observer, image_observer, picker_subscription],
@@ -1424,6 +1427,10 @@ impl Composer {
1424 1427 true
1425 1428 }
1426 1429
1430 fn side_input_focused(&self, window: &Window, cx: &App) -> bool {
1431 self.rewrite.input_focused(window, cx) || self.attach_menu.input_focused(window, cx)
1432 }
1433
1427 1434 fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1428 1435 self.focused_cell(window, cx).is_some()
1429 1436 }
@@ -1778,6 +1785,7 @@ impl Composer {
1778 1785 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1779 1786 self.conversation_id = Some(conversation_id.to_owned());
1780 1787 self.close_rewrite();
1788 self.close_attach_menu(window, cx);
1781 1789 self.cancel_uploads();
1782 1790 let dropped = if carry {
1783 1791 self.tray.keep_images_only()
@@ -2937,25 +2945,7 @@ impl Render for Composer {
2937 2945 picker.clone()
2938 2946 })
2939 2947 });
2940 let attach = can_attach.then(|| {
2941 div()
2942 .id("composer-attach")
2943 .size(px(COMPOSER_BUTTON_SIZE))
2944 .flex_none()
2945 .flex()
2946 .items_center()
2947 .justify_center()
2948 .rounded(px(8.))
2949 .cursor_pointer()
2950 .hover(|button| button.bg(theme::popup_hover()))
2951 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2952 .child(symbol(
2953 "attach_file",
2954 COMPOSER_ICON_SIZE,
2955 theme::text_muted(),
2956 ))
2957 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2958 });
2948 let attach = can_attach.then(|| self.render_attach_button(cx));
2959 2949 let markdown_mode = self.app.read(cx).markdown_mode;
2960 2950 let post_layout = self.post_layout();
2961 2951 let format_open = (self.format_bar_open() || post_layout) && !markdown_mode;
@@ -3210,18 +3200,27 @@ impl Render for Composer {
3210 3200 }
3211 3201 }))
3212 3202 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
3203 if this.side_input_focused(window, cx) {
3204 return;
3205 }
3213 3206 if this.link_editor.is_none() {
3214 3207 this.step_history(true, window, cx);
3215 3208 cx.stop_propagation();
3216 3209 }
3217 3210 }))
3218 3211 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
3212 if this.side_input_focused(window, cx) {
3213 return;
3214 }
3219 3215 if this.link_editor.is_none() {
3220 3216 this.step_history(false, window, cx);
3221 3217 cx.stop_propagation();
3222 3218 }
3223 3219 }))
3224 3220 .capture_action(cx.listener(|this, _: &Copy, window, cx| {
3221 if this.side_input_focused(window, cx) {
3222 return;
3223 }
3225 3224 if this.link_editor.is_none()
3226 3225 && !this.cell_has_focus(window, cx)
3227 3226 && this.copy_selection(cx)
@@ -3230,6 +3229,9 @@ impl Render for Composer {
3230 3229 }
3231 3230 }))
3232 3231 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
3232 if this.side_input_focused(window, cx) {
3233 return;
3234 }
3233 3235 if this.link_editor.is_none()
3234 3236 && !this.cell_has_focus(window, cx)
3235 3237 && this.copy_selection(cx)
@@ -3240,6 +3242,9 @@ impl Render for Composer {
3240 3242 }
3241 3243 }))
3242 3244 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
3245 if this.side_input_focused(window, cx) {
3246 return;
3247 }
3243 3248 if let Some(menu) = this.table_menu.as_mut() {
3244 3249 menu.step(-1);
3245 3250 cx.notify();
@@ -3265,6 +3270,9 @@ impl Render for Composer {
3265 3270 }
3266 3271 }))
3267 3272 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
3273 if this.side_input_focused(window, cx) {
3274 return;
3275 }
3268 3276 if let Some(menu) = this.table_menu.as_mut() {
3269 3277 menu.step(1);
3270 3278 cx.notify();
@@ -3285,6 +3293,9 @@ impl Render for Composer {
3285 3293 }
3286 3294 }))
3287 3295 .capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
3296 if this.side_input_focused(window, cx) {
3297 return;
3298 }
3288 3299 if this.link_editor.is_none()
3289 3300 && !this.cell_has_focus(window, cx)
3290 3301 && this.leave_quote(window, cx)
@@ -3293,6 +3304,9 @@ impl Render for Composer {
3293 3304 }
3294 3305 }))
3295 3306 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
3307 if this.side_input_focused(window, cx) {
3308 return;
3309 }
3296 3310 if this.table_menu.is_some() {
3297 3311 this.accept_table_menu(None, window, cx);
3298 3312 cx.stop_propagation();
@@ -3327,6 +3341,9 @@ impl Render for Composer {
3327 3341 }
3328 3342 }))
3329 3343 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
3344 if this.side_input_focused(window, cx) {
3345 return;
3346 }
3330 3347 if this.table_key(TableKey::Next, window, cx) {
3331 3348 cx.stop_propagation();
3332 3349 } else if this.link_editor.is_some() {
@@ -3338,6 +3355,9 @@ impl Render for Composer {
3338 3355 }
3339 3356 }))
3340 3357 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
3358 if this.side_input_focused(window, cx) {
3359 return;
3360 }
3341 3361 if this.table_key(TableKey::Previous, window, cx)
3342 3362 || (this.link_editor.is_none() && this.indent(true, window, cx))
3343 3363 {
@@ -3345,6 +3365,9 @@ impl Render for Composer {
3345 3365 }
3346 3366 }))
3347 3367 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
3368 if this.side_input_focused(window, cx) {
3369 return;
3370 }
3348 3371 if this.link_editor.is_none()
3349 3372 && !this.cell_has_focus(window, cx)
3350 3373 && (this.undo_conversion(window, cx)
@@ -3355,6 +3378,9 @@ impl Render for Composer {
3355 3378 }
3356 3379 }))
3357 3380 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
3381 if this.side_input_focused(window, cx) {
3382 return;
3383 }
3358 3384 if this.link_editor.is_none()
3359 3385 && !this.cell_has_focus(window, cx)
3360 3386 && (this.enter_table_beside(false, window, cx)
@@ -3379,6 +3405,10 @@ impl Render for Composer {
3379 3405 cx.stop_propagation();
3380 3406 return;
3381 3407 }
3408 if this.close_attach_menu(window, cx) {
3409 cx.stop_propagation();
3410 return;
3411 }
3382 3412 if this.close_rewrite() {
3383 3413 cx.notify();
3384 3414 cx.stop_propagation();
@@ -3423,6 +3453,7 @@ impl Render for Composer {
3423 3453 .children(self.render_schedule(cx))
3424 3454 .children(self.render_delivery_menu(cx))
3425 3455 .children(self.render_plus_menu(cx))
3456 .children(self.render_attach_menu(cx))
3426 3457 .children(self.render_rewrite_panel(cx))
3427 3458 .child(
3428 3459 v_flex()
@@ -31,6 +31,7 @@ use teams_core::{
31};
31};
32
32
33pub(crate) mod delivery;
33pub(crate) mod delivery;
34mod attach_menu;
34mod drafts;
35mod drafts;
35mod format_menus;
36mod format_menus;
36pub(crate) mod plus_menu;
37pub(crate) mod plus_menu;
@@ -260,6 +261,7 @@ pub struct Composer {
260 caret_text: String,
261 caret_text: String,
261 importance: store::MessageImportance,
262 importance: store::MessageImportance,
262 rewrite: rewrite::RewritePanel,
263 rewrite: rewrite::RewritePanel,
264 attach_menu: attach_menu::AttachMenu,
263 delivery_menu: bool,
265 delivery_menu: bool,
264 plus_menu: bool,
266 plus_menu: bool,
265 _subscriptions: [Subscription; 4],
267 _subscriptions: [Subscription; 4],
@@ -533,6 +535,7 @@ impl Composer {
533 caret_text: String::new(),
535 caret_text: String::new(),
534 importance: store::MessageImportance::Normal,
536 importance: store::MessageImportance::Normal,
535 rewrite: rewrite::RewritePanel::default(),
537 rewrite: rewrite::RewritePanel::default(),
538 attach_menu: attach_menu::AttachMenu::default(),
536 delivery_menu: false,
539 delivery_menu: false,
537 plus_menu: false,
540 plus_menu: false,
538 _subscriptions: [subscription, observer, image_observer, picker_subscription],
541 _subscriptions: [subscription, observer, image_observer, picker_subscription],
@@ -1424,6 +1427,10 @@ impl Composer {
1424 true
1427 true
1425 }
1428 }
1426
1429
1430 fn side_input_focused(&self, window: &Window, cx: &App) -> bool {
1431 self.rewrite.input_focused(window, cx) || self.attach_menu.input_focused(window, cx)
1432 }
1433
1427 fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1434 fn cell_has_focus(&self, window: &Window, cx: &App) -> bool {
1428 self.focused_cell(window, cx).is_some()
1435 self.focused_cell(window, cx).is_some()
1429 }
1436 }
@@ -1778,6 +1785,7 @@ impl Composer {
1778 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1785 let carry = self.carry_images_into.take().as_deref() == Some(conversation_id);
1779 self.conversation_id = Some(conversation_id.to_owned());
1786 self.conversation_id = Some(conversation_id.to_owned());
1780 self.close_rewrite();
1787 self.close_rewrite();
1788 self.close_attach_menu(window, cx);
1781 self.cancel_uploads();
1789 self.cancel_uploads();
1782 let dropped = if carry {
1790 let dropped = if carry {
1783 self.tray.keep_images_only()
1791 self.tray.keep_images_only()
@@ -2937,25 +2945,7 @@ impl Render for Composer {
2937 picker.clone()
2945 picker.clone()
2938 })
2946 })
2939 });
2947 });
2940 let attach = can_attach.then(|| {
2948 let attach = can_attach.then(|| self.render_attach_button(cx));
2941 div()
2942 .id("composer-attach")
2943 .size(px(COMPOSER_BUTTON_SIZE))
2944 .flex_none()
2945 .flex()
2946 .items_center()
2947 .justify_center()
2948 .rounded(px(8.))
2949 .cursor_pointer()
2950 .hover(|button| button.bg(theme::popup_hover()))
2951 .tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2952 .child(symbol(
2953 "attach_file",
2954 COMPOSER_ICON_SIZE,
2955 theme::text_muted(),
2956 ))
2957 .on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2958 });
2959 let markdown_mode = self.app.read(cx).markdown_mode;
2949 let markdown_mode = self.app.read(cx).markdown_mode;
2960 let post_layout = self.post_layout();
2950 let post_layout = self.post_layout();
2961 let format_open = (self.format_bar_open() || post_layout) && !markdown_mode;
2951 let format_open = (self.format_bar_open() || post_layout) && !markdown_mode;
@@ -3210,18 +3200,27 @@ impl Render for Composer {
3210 }
3200 }
3211 }))
3201 }))
3212 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
3202 .capture_action(cx.listener(|this, _: &Undo, window, cx| {
3203 if this.side_input_focused(window, cx) {
3204 return;
3205 }
3213 if this.link_editor.is_none() {
3206 if this.link_editor.is_none() {
3214 this.step_history(true, window, cx);
3207 this.step_history(true, window, cx);
3215 cx.stop_propagation();
3208 cx.stop_propagation();
3216 }
3209 }
3217 }))
3210 }))
3218 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
3211 .capture_action(cx.listener(|this, _: &Redo, window, cx| {
3212 if this.side_input_focused(window, cx) {
3213 return;
3214 }
3219 if this.link_editor.is_none() {
3215 if this.link_editor.is_none() {
3220 this.step_history(false, window, cx);
3216 this.step_history(false, window, cx);
3221 cx.stop_propagation();
3217 cx.stop_propagation();
3222 }
3218 }
3223 }))
3219 }))
3224 .capture_action(cx.listener(|this, _: &Copy, window, cx| {
3220 .capture_action(cx.listener(|this, _: &Copy, window, cx| {
3221 if this.side_input_focused(window, cx) {
3222 return;
3223 }
3225 if this.link_editor.is_none()
3224 if this.link_editor.is_none()
3226 && !this.cell_has_focus(window, cx)
3225 && !this.cell_has_focus(window, cx)
3227 && this.copy_selection(cx)
3226 && this.copy_selection(cx)
@@ -3230,6 +3229,9 @@ impl Render for Composer {
3230 }
3229 }
3231 }))
3230 }))
3232 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
3231 .capture_action(cx.listener(|this, _: &Cut, window, cx| {
3232 if this.side_input_focused(window, cx) {
3233 return;
3234 }
3233 if this.link_editor.is_none()
3235 if this.link_editor.is_none()
3234 && !this.cell_has_focus(window, cx)
3236 && !this.cell_has_focus(window, cx)
3235 && this.copy_selection(cx)
3237 && this.copy_selection(cx)
@@ -3240,6 +3242,9 @@ impl Render for Composer {
3240 }
3242 }
3241 }))
3243 }))
3242 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
3244 .capture_action(cx.listener(|this, _: &MoveUp, window, cx| {
3245 if this.side_input_focused(window, cx) {
3246 return;
3247 }
3243 if let Some(menu) = this.table_menu.as_mut() {
3248 if let Some(menu) = this.table_menu.as_mut() {
3244 menu.step(-1);
3249 menu.step(-1);
3245 cx.notify();
3250 cx.notify();
@@ -3265,6 +3270,9 @@ impl Render for Composer {
3265 }
3270 }
3266 }))
3271 }))
3267 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
3272 .capture_action(cx.listener(|this, _: &MoveDown, window, cx| {
3273 if this.side_input_focused(window, cx) {
3274 return;
3275 }
3268 if let Some(menu) = this.table_menu.as_mut() {
3276 if let Some(menu) = this.table_menu.as_mut() {
3269 menu.step(1);
3277 menu.step(1);
3270 cx.notify();
3278 cx.notify();
@@ -3285,6 +3293,9 @@ impl Render for Composer {
3285 }
3293 }
3286 }))
3294 }))
3287 .capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
3295 .capture_action(cx.listener(|this, _: &MoveRight, window, cx| {
3296 if this.side_input_focused(window, cx) {
3297 return;
3298 }
3288 if this.link_editor.is_none()
3299 if this.link_editor.is_none()
3289 && !this.cell_has_focus(window, cx)
3300 && !this.cell_has_focus(window, cx)
3290 && this.leave_quote(window, cx)
3301 && this.leave_quote(window, cx)
@@ -3293,6 +3304,9 @@ impl Render for Composer {
3293 }
3304 }
3294 }))
3305 }))
3295 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
3306 .capture_action(cx.listener(|this, action: &Enter, window, cx| {
3307 if this.side_input_focused(window, cx) {
3308 return;
3309 }
3296 if this.table_menu.is_some() {
3310 if this.table_menu.is_some() {
3297 this.accept_table_menu(None, window, cx);
3311 this.accept_table_menu(None, window, cx);
3298 cx.stop_propagation();
3312 cx.stop_propagation();
@@ -3327,6 +3341,9 @@ impl Render for Composer {
3327 }
3341 }
3328 }))
3342 }))
3329 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
3343 .capture_action(cx.listener(|this, _: &IndentInline, window, cx| {
3344 if this.side_input_focused(window, cx) {
3345 return;
3346 }
3330 if this.table_key(TableKey::Next, window, cx) {
3347 if this.table_key(TableKey::Next, window, cx) {
3331 cx.stop_propagation();
3348 cx.stop_propagation();
3332 } else if this.link_editor.is_some() {
3349 } else if this.link_editor.is_some() {
@@ -3338,6 +3355,9 @@ impl Render for Composer {
3338 }
3355 }
3339 }))
3356 }))
3340 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
3357 .capture_action(cx.listener(|this, _: &OutdentInline, window, cx| {
3358 if this.side_input_focused(window, cx) {
3359 return;
3360 }
3341 if this.table_key(TableKey::Previous, window, cx)
3361 if this.table_key(TableKey::Previous, window, cx)
3342 || (this.link_editor.is_none() && this.indent(true, window, cx))
3362 || (this.link_editor.is_none() && this.indent(true, window, cx))
3343 {
3363 {
@@ -3345,6 +3365,9 @@ impl Render for Composer {
3345 }
3365 }
3346 }))
3366 }))
3347 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
3367 .capture_action(cx.listener(|this, _: &Backspace, window, cx| {
3368 if this.side_input_focused(window, cx) {
3369 return;
3370 }
3348 if this.link_editor.is_none()
3371 if this.link_editor.is_none()
3349 && !this.cell_has_focus(window, cx)
3372 && !this.cell_has_focus(window, cx)
3350 && (this.undo_conversion(window, cx)
3373 && (this.undo_conversion(window, cx)
@@ -3355,6 +3378,9 @@ impl Render for Composer {
3355 }
3378 }
3356 }))
3379 }))
3357 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
3380 .capture_action(cx.listener(|this, _: &Delete, window, cx| {
3381 if this.side_input_focused(window, cx) {
3382 return;
3383 }
3358 if this.link_editor.is_none()
3384 if this.link_editor.is_none()
3359 && !this.cell_has_focus(window, cx)
3385 && !this.cell_has_focus(window, cx)
3360 && (this.enter_table_beside(false, window, cx)
3386 && (this.enter_table_beside(false, window, cx)
@@ -3379,6 +3405,10 @@ impl Render for Composer {
3379 cx.stop_propagation();
3405 cx.stop_propagation();
3380 return;
3406 return;
3381 }
3407 }
3408 if this.close_attach_menu(window, cx) {
3409 cx.stop_propagation();
3410 return;
3411 }
3382 if this.close_rewrite() {
3412 if this.close_rewrite() {
3383 cx.notify();
3413 cx.notify();
3384 cx.stop_propagation();
3414 cx.stop_propagation();
@@ -3423,6 +3453,7 @@ impl Render for Composer {
3423 .children(self.render_schedule(cx))
3453 .children(self.render_schedule(cx))
3424 .children(self.render_delivery_menu(cx))
3454 .children(self.render_delivery_menu(cx))
3425 .children(self.render_plus_menu(cx))
3455 .children(self.render_plus_menu(cx))
3456 .children(self.render_attach_menu(cx))
3426 .children(self.render_rewrite_panel(cx))
3457 .children(self.render_rewrite_panel(cx))
3427 .child(
3458 .child(
3428 v_flex()
3459 v_flex()
crates/app/src/views/composer/attach_menu.rs added +442 −0
@@ -0,0 +1,442 @@
1 use std::time::Duration;
2
3 use chrono::{DateTime, Utc};
4 use gpui_kit::component::fluent::{
5 MENU_ICON_LABEL_GAP, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
6 };
7 use gpui_kit::component::input::{Input, InputEvent, InputState};
8 use gpui_kit::component::scroll::ScrollableElement as _;
9 use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
10 use gpui_kit::component::{h_flex, v_flex};
11 use gpui_kit::prelude::FluentBuilder as _;
12 use gpui_kit::*;
13 use teams_core::substrate_search::SearchSession;
14 use teams_core::{CloudFile, FileKind, FileReference};
15
16 use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
17 use crate::runtime;
18 use crate::theme::{self, ElevatedSurface as _};
19 use crate::views::attachments::file_badge;
20 use crate::views::widgets::symbol;
21
22 pub const ATTACH_BUTTON_TAG: &str = "composer/actions/attach";
23 pub const ATTACH_MENU_TAG: &str = "composer/attach-menu";
24 const BUTTON_LABEL: &str = "Attach file";
25 const SEARCH_PLACEHOLDER: &str = "Search cloud files";
26 const RECENT_TITLE: &str = "Recent cloud files";
27 const RESULTS_TITLE: &str = "Cloud files";
28 const UPLOAD_LABEL: &str = "Upload from this device";
29 const LOADING: &str = "Loading ...";
30 const NO_RECENT: &str = "Your recent files will show up here.";
31 const NO_RESULTS: &str = "No files found.";
32 const FAILED: &str = "Couldn't load files.";
33 const ATTACH_FAILED: &str = "Couldn't attach";
34 const MENU_WIDTH: f32 = 316.;
35 const LIST_MAX_HEIGHT: f32 = 300.;
36 const ROW_HEIGHT: f32 = 48.;
37 const BADGE_SIZE: f32 = 24.;
38 const SEARCH_HEIGHT: f32 = 32.;
39 const SIDE_INSET: f32 = 12.;
40 const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
41 const MINUTE: i64 = 60;
42 const HOUR: i64 = 60 * MINUTE;
43 const DAY: i64 = 24 * HOUR;
44
45 #[derive(Default)]
46 pub(super) struct AttachMenu {
47 pub(super) open: bool,
48 recent: Listing,
49 found: Option<Listing>,
50 search_input: Option<Entity<InputState>>,
51 search_session: Option<SearchSession>,
52 search_generation: u64,
53 search_task: Option<Task<()>>,
54 _search_events: Option<Subscription>,
55 }
56
57 impl AttachMenu {
58 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
59 self.search_input
60 .as_ref()
61 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
62 }
63 }
64
65 #[derive(Default)]
66 enum Listing {
67 #[default]
68 Loading,
69 Ready(Vec<CloudFile>),
70 Failed,
71 }
72
73 pub fn opened_label(opened: DateTime<Utc>, now: DateTime<Utc>) -> String {
74 let seconds = (now - opened).num_seconds().max(0);
75 let count = |value: i64, unit: &str| {
76 let plural = if value == 1 { "" } else { "s" };
77 format!("Opened {value} {unit}{plural} ago")
78 };
79 match seconds {
80 0..MINUTE => "Opened just now".to_owned(),
81 MINUTE..HOUR => count(seconds / MINUTE, "minute"),
82 HOUR..DAY => count(seconds / HOUR, "hour"),
83 _ => count(seconds / DAY, "day"),
84 }
85 }
86
87 fn demo_files() -> Vec<CloudFile> {
88 let now = Utc::now();
89 [
90 ("Release plan Q4.pptx", 2_480_000, 4 * HOUR),
91 ("Architecture review.pdf", 860_000, 2 * DAY),
92 ("Budget 2027.xlsx", 74_000, 9 * DAY),
93 ]
94 .into_iter()
95 .map(|(name, size, age)| CloudFile {
96 name: name.to_owned(),
97 size,
98 web_url: format!("https://contoso.sharepoint.com/demo/{name}"),
99 drive_id: None,
100 item_id: None,
101 last_opened: Some(now - chrono::Duration::seconds(age)),
102 })
103 .collect()
104 }
105
106 impl Composer {
107 pub(super) fn render_attach_button(&self, cx: &mut Context<Self>) -> Stateful<Div> {
108 let open = self.attach_menu.open;
109 div()
110 .id("composer-attach")
111 .debug_selector(|| ATTACH_BUTTON_TAG.into())
112 .size(px(COMPOSER_BUTTON_SIZE))
113 .flex_none()
114 .flex()
115 .items_center()
116 .justify_center()
117 .rounded(px(8.))
118 .cursor_pointer()
119 .when(open, |button| button.bg(theme::popup_hover()))
120 .hover(|button| button.bg(theme::popup_hover()))
121 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
122 .child(symbol(
123 "attach_file",
124 COMPOSER_ICON_SIZE,
125 if open { theme::accent_text() } else { theme::text_muted() },
126 ))
127 .on_mouse_down(MouseButton::Left, |_, window, cx| {
128 window.prevent_default();
129 cx.stop_propagation();
130 })
131 .on_click(cx.listener(|this, _, window, cx| this.toggle_attach_menu(window, cx)))
132 }
133
134 fn toggle_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
135 if self.attach_menu.open {
136 self.close_attach_menu(window, cx);
137 return;
138 }
139 self.attach_menu.open = true;
140 self.plus_menu = false;
141 self.load_recent_cloud_files(cx);
142 let input = self.attach_search_input(window, cx);
143 input.update(cx, |input, cx| input.focus(window, cx));
144 cx.notify();
145 }
146
147 pub(super) fn close_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
148 if !self.attach_menu.open {
149 return false;
150 }
151 self.attach_menu.open = false;
152 self.attach_menu.found = None;
153 self.attach_menu.search_task = None;
154 self.attach_menu.search_generation += 1;
155 if let Some(input) = &self.attach_menu.search_input {
156 input.update(cx, |input, cx| input.set_value("", window, cx));
157 }
158 self.focus(window, cx);
159 cx.notify();
160 true
161 }
162
163 fn attach_search_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
164 if let Some(input) = &self.attach_menu.search_input {
165 return input.clone();
166 }
167 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
168 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
169 if matches!(event, InputEvent::Change) {
170 let text = input.read(cx).value().trim().to_owned();
171 this.search_cloud_files(text, cx);
172 }
173 });
174 self.attach_menu.search_input = Some(input.clone());
175 self.attach_menu._search_events = Some(subscription);
176 input
177 }
178
179 fn load_recent_cloud_files(&mut self, cx: &mut Context<Self>) {
180 let state = self.app.read(cx);
181 if state.mode.demo {
182 self.attach_menu.recent = Listing::Ready(demo_files());
183 return;
184 }
185 let Some(engine) = state.engine.clone() else {
186 self.attach_menu.recent = Listing::Failed;
187 return;
188 };
189 if !matches!(self.attach_menu.recent, Listing::Ready(_)) {
190 self.attach_menu.recent = Listing::Loading;
191 }
192 let receiver = runtime::spawn(async move { engine.recent_cloud_files().await });
193 cx.spawn(async move |this, cx| {
194 let listing = match receiver.await {
195 Ok(Ok(files)) => Listing::Ready(files),
196 _ => Listing::Failed,
197 };
198 this.update(cx, |this, cx| {
199 if !matches!(listing, Listing::Failed) || !matches!(this.attach_menu.recent, Listing::Ready(_)) {
200 this.attach_menu.recent = listing;
201 }
202 cx.notify();
203 })
204 .ok();
205 })
206 .detach();
207 }
208
209 fn search_cloud_files(&mut self, text: String, cx: &mut Context<Self>) {
210 self.attach_menu.search_generation += 1;
211 let generation = self.attach_menu.search_generation;
212 if text.is_empty() {
213 self.attach_menu.found = None;
214 self.attach_menu.search_task = None;
215 cx.notify();
216 return;
217 }
218 let state = self.app.read(cx);
219 if state.mode.demo {
220 let needle = text.to_lowercase();
221 let matches = demo_files()
222 .into_iter()
223 .filter(|file| file.name.to_lowercase().contains(&needle))
224 .collect();
225 self.attach_menu.found = Some(Listing::Ready(matches));
226 cx.notify();
227 return;
228 }
229 let Some(engine) = state.engine.clone() else {
230 return;
231 };
232 let search_session = self.attach_menu.search_session.get_or_insert_with(SearchSession::new).clone();
233 self.attach_menu.found = Some(Listing::Loading);
234 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
235 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
236 let receiver = runtime::spawn(async move { engine.search_cloud_files(&search_session, &text).await });
237 let listing = match receiver.await {
238 Ok(Ok(files)) => Listing::Ready(files),
239 _ => Listing::Failed,
240 };
241 this.update(cx, |this, cx| {
242 if this.attach_menu.search_generation == generation {
243 this.attach_menu.found = Some(listing);
244 cx.notify();
245 }
246 })
247 .ok();
248 }));
249 cx.notify();
250 }
251
252 fn attach_cloud_file(&mut self, file: CloudFile, window: &mut Window, cx: &mut Context<Self>) {
253 self.close_attach_menu(window, cx);
254 let state = self.app.read(cx);
255 if state.mode.demo {
256 let reference = FileReference {
257 attachment_id: uuid::Uuid::new_v4().to_string(),
258 content_url: file.web_url.clone(),
259 name: file.name.clone(),
260 };
261 self.tray.add_cloud_file(file.name, file.size, reference);
262 self.schedule_draft_save(cx);
263 cx.notify();
264 return;
265 }
266 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id.clone()) else {
267 return;
268 };
269 let task_file = file.clone();
270 let receiver =
271 runtime::spawn(async move { engine.attach_cloud_file(&conversation_id, &task_file).await });
272 cx.spawn(async move |this, cx| {
273 let attached = receiver.await;
274 this.update(cx, |this, cx| {
275 match attached {
276 Ok(Ok(reference)) => {
277 this.tray.add_cloud_file(file.name, file.size, reference);
278 this.schedule_draft_save(cx);
279 }
280 _ => this.tray.set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
281 }
282 cx.notify();
283 })
284 .ok();
285 })
286 .detach();
287 }
288
289 pub(super) fn render_attach_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
290 if !self.attach_menu.open {
291 return None;
292 }
293 let search = self.attach_menu.search_input.clone().map(|input| {
294 h_flex()
295 .mx(px(SIDE_INSET))
296 .mt(px(4.))
297 .h(px(SEARCH_HEIGHT))
298 .px(px(10.))
299 .gap(px(8.))
300 .items_center()
301 .rounded(px(6.))
302 .bg(theme::surface_raised())
303 .child(symbol("search", 16., theme::text_muted()))
304 .child(div().flex_1().min_w_0().child(Input::new(&input).appearance(false).bordered(false)))
305 });
306 let (title, listing) = match &self.attach_menu.found {
307 Some(found) => (RESULTS_TITLE, found),
308 None => (RECENT_TITLE, &self.attach_menu.recent),
309 };
310 let now = Utc::now();
311 let body = match listing {
312 Listing::Loading => vec![self.menu_note(LOADING)],
313 Listing::Failed => vec![self.menu_note(FAILED)],
314 Listing::Ready(files) if files.is_empty() => {
315 vec![self.menu_note(if self.attach_menu.found.is_some() { NO_RESULTS } else { NO_RECENT })]
316 }
317 Listing::Ready(files) => files
318 .iter()
319 .enumerate()
320 .map(|(index, file)| self.cloud_file_row(index, file, now, cx).into_any_element())
321 .collect(),
322 };
323 let upload = h_flex()
324 .id("composer-attach-upload")
325 .w_full()
326 .h(MENU_ITEM_HEIGHT)
327 .px(MENU_ITEM_PADDING_X)
328 .gap(MENU_ICON_LABEL_GAP)
329 .items_center()
330 .rounded(px(6.))
331 .cursor_pointer()
332 .hover(|row| row.bg(theme::popup_hover()))
333 .child(symbol("upload", 16., theme::text_soft()))
334 .child(div().text_size(px(13.)).text_color(theme::text()).child(UPLOAD_LABEL))
335 .on_click(cx.listener(|this, _, window, cx| {
336 this.close_attach_menu(window, cx);
337 this.open_picker(window, cx);
338 }));
339 Some(
340 v_flex()
341 .id(ATTACH_MENU_TAG)
342 .debug_selector(|| ATTACH_MENU_TAG.into())
343 .absolute()
344 .bottom(relative(1.))
345 .right_0()
346 .mb(px(6.))
347 .w(px(MENU_WIDTH))
348 .max_w(relative(1.))
349 .py(MENU_LIST_PADDING)
350 .gap(MENU_ITEM_GAP)
351 .rounded(px(10.))
352 .flyout_surface()
353 .occlude()
354 .on_mouse_down_out(cx.listener(|this, _, window, cx| {
355 this.close_attach_menu(window, cx);
356 }))
357 .children(search)
358 .child(
359 div()
360 .px(px(SIDE_INSET))
361 .pt(px(6.))
362 .text_size(px(13.))
363 .font_weight(FontWeight::SEMIBOLD)
364 .text_color(theme::text())
365 .child(title),
366 )
367 .child(
368 v_flex()
369 .id("composer-attach-list")
370 .max_h(px(LIST_MAX_HEIGHT))
371 .px(MENU_LIST_PADDING)
372 .overflow_y_scrollbar()
373 .children(body),
374 )
375 .child(div().w_full().h(px(1.)).bg(theme::border()))
376 .child(div().px(MENU_LIST_PADDING).child(upload))
377 .into_any_element(),
378 )
379 }
380
381 fn menu_note(&self, text: &'static str) -> AnyElement {
382 div()
383 .px(MENU_ITEM_PADDING_X)
384 .py(px(10.))
385 .text_size(px(12.))
386 .text_color(theme::text_soft())
387 .child(text)
388 .into_any_element()
389 }
390
391 fn cloud_file_row(&self, index: usize, file: &CloudFile, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
392 let picked = file.clone();
393 h_flex()
394 .id(("composer-attach-file", index))
395 .w_full()
396 .h(px(ROW_HEIGHT))
397 .flex_none()
398 .px(MENU_ITEM_PADDING_X)
399 .gap(px(10.))
400 .items_center()
401 .rounded(px(6.))
402 .cursor_pointer()
403 .hover(|row| row.bg(theme::popup_hover()))
404 .child(file_badge(FileKind::from_name(&file.name), BADGE_SIZE))
405 .child(
406 v_flex()
407 .flex_1()
408 .min_w_0()
409 .child(
410 div()
411 .text_size(px(13.))
412 .text_color(theme::text())
413 .truncate()
414 .child(file.name.clone()),
415 )
416 .children(file.last_opened.map(|opened| {
417 div()
418 .text_size(px(12.))
419 .text_color(theme::text_soft())
420 .child(opened_label(opened, now))
421 })),
422 )
423 .on_click(cx.listener(move |this, _, window, cx| this.attach_cloud_file(picked.clone(), window, cx)))
424 }
425 }
426
427 #[cfg(test)]
428 mod tests {
429 use chrono::TimeZone as _;
430
431 use super::opened_label;
432
433 #[test]
434 fn opened_reads_like_teams() {
435 let now = chrono::Utc.with_ymd_and_hms(2026, 11, 9, 20, 0, 0).unwrap();
436 let ago = |seconds: i64| opened_label(now - chrono::Duration::seconds(seconds), now);
437 assert_eq!(ago(20), "Opened just now");
438 assert_eq!(ago(60), "Opened 1 minute ago");
439 assert_eq!(ago(4 * 3600 + 100), "Opened 4 hours ago");
440 assert_eq!(ago(6 * 86_400), "Opened 6 days ago");
441 }
442 }
@@ -0,0 +1,442 @@
1use std::time::Duration;
2
3use chrono::{DateTime, Utc};
4use gpui_kit::component::fluent::{
5 MENU_ICON_LABEL_GAP, MENU_ITEM_GAP, MENU_ITEM_HEIGHT, MENU_ITEM_PADDING_X, MENU_LIST_PADDING,
6};
7use gpui_kit::component::input::{Input, InputEvent, InputState};
8use gpui_kit::component::scroll::ScrollableElement as _;
9use gpui_kit::component::tooltip::PopupTriggerTooltip as _;
10use gpui_kit::component::{h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13use teams_core::substrate_search::SearchSession;
14use teams_core::{CloudFile, FileKind, FileReference};
15
16use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer};
17use crate::runtime;
18use crate::theme::{self, ElevatedSurface as _};
19use crate::views::attachments::file_badge;
20use crate::views::widgets::symbol;
21
22pub const ATTACH_BUTTON_TAG: &str = "composer/actions/attach";
23pub const ATTACH_MENU_TAG: &str = "composer/attach-menu";
24const BUTTON_LABEL: &str = "Attach file";
25const SEARCH_PLACEHOLDER: &str = "Search cloud files";
26const RECENT_TITLE: &str = "Recent cloud files";
27const RESULTS_TITLE: &str = "Cloud files";
28const UPLOAD_LABEL: &str = "Upload from this device";
29const LOADING: &str = "Loading ...";
30const NO_RECENT: &str = "Your recent files will show up here.";
31const NO_RESULTS: &str = "No files found.";
32const FAILED: &str = "Couldn't load files.";
33const ATTACH_FAILED: &str = "Couldn't attach";
34const MENU_WIDTH: f32 = 316.;
35const LIST_MAX_HEIGHT: f32 = 300.;
36const ROW_HEIGHT: f32 = 48.;
37const BADGE_SIZE: f32 = 24.;
38const SEARCH_HEIGHT: f32 = 32.;
39const SIDE_INSET: f32 = 12.;
40const SEARCH_DEBOUNCE: Duration = Duration::from_millis(300);
41const MINUTE: i64 = 60;
42const HOUR: i64 = 60 * MINUTE;
43const DAY: i64 = 24 * HOUR;
44
45#[derive(Default)]
46pub(super) struct AttachMenu {
47 pub(super) open: bool,
48 recent: Listing,
49 found: Option<Listing>,
50 search_input: Option<Entity<InputState>>,
51 search_session: Option<SearchSession>,
52 search_generation: u64,
53 search_task: Option<Task<()>>,
54 _search_events: Option<Subscription>,
55}
56
57impl AttachMenu {
58 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
59 self.search_input
60 .as_ref()
61 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
62 }
63}
64
65#[derive(Default)]
66enum Listing {
67 #[default]
68 Loading,
69 Ready(Vec<CloudFile>),
70 Failed,
71}
72
73pub fn opened_label(opened: DateTime<Utc>, now: DateTime<Utc>) -> String {
74 let seconds = (now - opened).num_seconds().max(0);
75 let count = |value: i64, unit: &str| {
76 let plural = if value == 1 { "" } else { "s" };
77 format!("Opened {value} {unit}{plural} ago")
78 };
79 match seconds {
80 0..MINUTE => "Opened just now".to_owned(),
81 MINUTE..HOUR => count(seconds / MINUTE, "minute"),
82 HOUR..DAY => count(seconds / HOUR, "hour"),
83 _ => count(seconds / DAY, "day"),
84 }
85}
86
87fn demo_files() -> Vec<CloudFile> {
88 let now = Utc::now();
89 [
90 ("Release plan Q4.pptx", 2_480_000, 4 * HOUR),
91 ("Architecture review.pdf", 860_000, 2 * DAY),
92 ("Budget 2027.xlsx", 74_000, 9 * DAY),
93 ]
94 .into_iter()
95 .map(|(name, size, age)| CloudFile {
96 name: name.to_owned(),
97 size,
98 web_url: format!("https://contoso.sharepoint.com/demo/{name}"),
99 drive_id: None,
100 item_id: None,
101 last_opened: Some(now - chrono::Duration::seconds(age)),
102 })
103 .collect()
104}
105
106impl Composer {
107 pub(super) fn render_attach_button(&self, cx: &mut Context<Self>) -> Stateful<Div> {
108 let open = self.attach_menu.open;
109 div()
110 .id("composer-attach")
111 .debug_selector(|| ATTACH_BUTTON_TAG.into())
112 .size(px(COMPOSER_BUTTON_SIZE))
113 .flex_none()
114 .flex()
115 .items_center()
116 .justify_center()
117 .rounded(px(8.))
118 .cursor_pointer()
119 .when(open, |button| button.bg(theme::popup_hover()))
120 .hover(|button| button.bg(theme::popup_hover()))
121 .popup_trigger_tooltip_text(open, BUTTON_LABEL)
122 .child(symbol(
123 "attach_file",
124 COMPOSER_ICON_SIZE,
125 if open { theme::accent_text() } else { theme::text_muted() },
126 ))
127 .on_mouse_down(MouseButton::Left, |_, window, cx| {
128 window.prevent_default();
129 cx.stop_propagation();
130 })
131 .on_click(cx.listener(|this, _, window, cx| this.toggle_attach_menu(window, cx)))
132 }
133
134 fn toggle_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
135 if self.attach_menu.open {
136 self.close_attach_menu(window, cx);
137 return;
138 }
139 self.attach_menu.open = true;
140 self.plus_menu = false;
141 self.load_recent_cloud_files(cx);
142 let input = self.attach_search_input(window, cx);
143 input.update(cx, |input, cx| input.focus(window, cx));
144 cx.notify();
145 }
146
147 pub(super) fn close_attach_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
148 if !self.attach_menu.open {
149 return false;
150 }
151 self.attach_menu.open = false;
152 self.attach_menu.found = None;
153 self.attach_menu.search_task = None;
154 self.attach_menu.search_generation += 1;
155 if let Some(input) = &self.attach_menu.search_input {
156 input.update(cx, |input, cx| input.set_value("", window, cx));
157 }
158 self.focus(window, cx);
159 cx.notify();
160 true
161 }
162
163 fn attach_search_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
164 if let Some(input) = &self.attach_menu.search_input {
165 return input.clone();
166 }
167 let input = cx.new(|cx| InputState::new(window, cx).placeholder(SEARCH_PLACEHOLDER));
168 let subscription = cx.subscribe_in(&input, window, |this, input, event: &InputEvent, _, cx| {
169 if matches!(event, InputEvent::Change) {
170 let text = input.read(cx).value().trim().to_owned();
171 this.search_cloud_files(text, cx);
172 }
173 });
174 self.attach_menu.search_input = Some(input.clone());
175 self.attach_menu._search_events = Some(subscription);
176 input
177 }
178
179 fn load_recent_cloud_files(&mut self, cx: &mut Context<Self>) {
180 let state = self.app.read(cx);
181 if state.mode.demo {
182 self.attach_menu.recent = Listing::Ready(demo_files());
183 return;
184 }
185 let Some(engine) = state.engine.clone() else {
186 self.attach_menu.recent = Listing::Failed;
187 return;
188 };
189 if !matches!(self.attach_menu.recent, Listing::Ready(_)) {
190 self.attach_menu.recent = Listing::Loading;
191 }
192 let receiver = runtime::spawn(async move { engine.recent_cloud_files().await });
193 cx.spawn(async move |this, cx| {
194 let listing = match receiver.await {
195 Ok(Ok(files)) => Listing::Ready(files),
196 _ => Listing::Failed,
197 };
198 this.update(cx, |this, cx| {
199 if !matches!(listing, Listing::Failed) || !matches!(this.attach_menu.recent, Listing::Ready(_)) {
200 this.attach_menu.recent = listing;
201 }
202 cx.notify();
203 })
204 .ok();
205 })
206 .detach();
207 }
208
209 fn search_cloud_files(&mut self, text: String, cx: &mut Context<Self>) {
210 self.attach_menu.search_generation += 1;
211 let generation = self.attach_menu.search_generation;
212 if text.is_empty() {
213 self.attach_menu.found = None;
214 self.attach_menu.search_task = None;
215 cx.notify();
216 return;
217 }
218 let state = self.app.read(cx);
219 if state.mode.demo {
220 let needle = text.to_lowercase();
221 let matches = demo_files()
222 .into_iter()
223 .filter(|file| file.name.to_lowercase().contains(&needle))
224 .collect();
225 self.attach_menu.found = Some(Listing::Ready(matches));
226 cx.notify();
227 return;
228 }
229 let Some(engine) = state.engine.clone() else {
230 return;
231 };
232 let search_session = self.attach_menu.search_session.get_or_insert_with(SearchSession::new).clone();
233 self.attach_menu.found = Some(Listing::Loading);
234 self.attach_menu.search_task = Some(cx.spawn(async move |this, cx| {
235 cx.background_executor().timer(SEARCH_DEBOUNCE).await;
236 let receiver = runtime::spawn(async move { engine.search_cloud_files(&search_session, &text).await });
237 let listing = match receiver.await {
238 Ok(Ok(files)) => Listing::Ready(files),
239 _ => Listing::Failed,
240 };
241 this.update(cx, |this, cx| {
242 if this.attach_menu.search_generation == generation {
243 this.attach_menu.found = Some(listing);
244 cx.notify();
245 }
246 })
247 .ok();
248 }));
249 cx.notify();
250 }
251
252 fn attach_cloud_file(&mut self, file: CloudFile, window: &mut Window, cx: &mut Context<Self>) {
253 self.close_attach_menu(window, cx);
254 let state = self.app.read(cx);
255 if state.mode.demo {
256 let reference = FileReference {
257 attachment_id: uuid::Uuid::new_v4().to_string(),
258 content_url: file.web_url.clone(),
259 name: file.name.clone(),
260 };
261 self.tray.add_cloud_file(file.name, file.size, reference);
262 self.schedule_draft_save(cx);
263 cx.notify();
264 return;
265 }
266 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id.clone()) else {
267 return;
268 };
269 let task_file = file.clone();
270 let receiver =
271 runtime::spawn(async move { engine.attach_cloud_file(&conversation_id, &task_file).await });
272 cx.spawn(async move |this, cx| {
273 let attached = receiver.await;
274 this.update(cx, |this, cx| {
275 match attached {
276 Ok(Ok(reference)) => {
277 this.tray.add_cloud_file(file.name, file.size, reference);
278 this.schedule_draft_save(cx);
279 }
280 _ => this.tray.set_notice(format!("{ATTACH_FAILED} {}.", file.name)),
281 }
282 cx.notify();
283 })
284 .ok();
285 })
286 .detach();
287 }
288
289 pub(super) fn render_attach_menu(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
290 if !self.attach_menu.open {
291 return None;
292 }
293 let search = self.attach_menu.search_input.clone().map(|input| {
294 h_flex()
295 .mx(px(SIDE_INSET))
296 .mt(px(4.))
297 .h(px(SEARCH_HEIGHT))
298 .px(px(10.))
299 .gap(px(8.))
300 .items_center()
301 .rounded(px(6.))
302 .bg(theme::surface_raised())
303 .child(symbol("search", 16., theme::text_muted()))
304 .child(div().flex_1().min_w_0().child(Input::new(&input).appearance(false).bordered(false)))
305 });
306 let (title, listing) = match &self.attach_menu.found {
307 Some(found) => (RESULTS_TITLE, found),
308 None => (RECENT_TITLE, &self.attach_menu.recent),
309 };
310 let now = Utc::now();
311 let body = match listing {
312 Listing::Loading => vec![self.menu_note(LOADING)],
313 Listing::Failed => vec![self.menu_note(FAILED)],
314 Listing::Ready(files) if files.is_empty() => {
315 vec![self.menu_note(if self.attach_menu.found.is_some() { NO_RESULTS } else { NO_RECENT })]
316 }
317 Listing::Ready(files) => files
318 .iter()
319 .enumerate()
320 .map(|(index, file)| self.cloud_file_row(index, file, now, cx).into_any_element())
321 .collect(),
322 };
323 let upload = h_flex()
324 .id("composer-attach-upload")
325 .w_full()
326 .h(MENU_ITEM_HEIGHT)
327 .px(MENU_ITEM_PADDING_X)
328 .gap(MENU_ICON_LABEL_GAP)
329 .items_center()
330 .rounded(px(6.))
331 .cursor_pointer()
332 .hover(|row| row.bg(theme::popup_hover()))
333 .child(symbol("upload", 16., theme::text_soft()))
334 .child(div().text_size(px(13.)).text_color(theme::text()).child(UPLOAD_LABEL))
335 .on_click(cx.listener(|this, _, window, cx| {
336 this.close_attach_menu(window, cx);
337 this.open_picker(window, cx);
338 }));
339 Some(
340 v_flex()
341 .id(ATTACH_MENU_TAG)
342 .debug_selector(|| ATTACH_MENU_TAG.into())
343 .absolute()
344 .bottom(relative(1.))
345 .right_0()
346 .mb(px(6.))
347 .w(px(MENU_WIDTH))
348 .max_w(relative(1.))
349 .py(MENU_LIST_PADDING)
350 .gap(MENU_ITEM_GAP)
351 .rounded(px(10.))
352 .flyout_surface()
353 .occlude()
354 .on_mouse_down_out(cx.listener(|this, _, window, cx| {
355 this.close_attach_menu(window, cx);
356 }))
357 .children(search)
358 .child(
359 div()
360 .px(px(SIDE_INSET))
361 .pt(px(6.))
362 .text_size(px(13.))
363 .font_weight(FontWeight::SEMIBOLD)
364 .text_color(theme::text())
365 .child(title),
366 )
367 .child(
368 v_flex()
369 .id("composer-attach-list")
370 .max_h(px(LIST_MAX_HEIGHT))
371 .px(MENU_LIST_PADDING)
372 .overflow_y_scrollbar()
373 .children(body),
374 )
375 .child(div().w_full().h(px(1.)).bg(theme::border()))
376 .child(div().px(MENU_LIST_PADDING).child(upload))
377 .into_any_element(),
378 )
379 }
380
381 fn menu_note(&self, text: &'static str) -> AnyElement {
382 div()
383 .px(MENU_ITEM_PADDING_X)
384 .py(px(10.))
385 .text_size(px(12.))
386 .text_color(theme::text_soft())
387 .child(text)
388 .into_any_element()
389 }
390
391 fn cloud_file_row(&self, index: usize, file: &CloudFile, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
392 let picked = file.clone();
393 h_flex()
394 .id(("composer-attach-file", index))
395 .w_full()
396 .h(px(ROW_HEIGHT))
397 .flex_none()
398 .px(MENU_ITEM_PADDING_X)
399 .gap(px(10.))
400 .items_center()
401 .rounded(px(6.))
402 .cursor_pointer()
403 .hover(|row| row.bg(theme::popup_hover()))
404 .child(file_badge(FileKind::from_name(&file.name), BADGE_SIZE))
405 .child(
406 v_flex()
407 .flex_1()
408 .min_w_0()
409 .child(
410 div()
411 .text_size(px(13.))
412 .text_color(theme::text())
413 .truncate()
414 .child(file.name.clone()),
415 )
416 .children(file.last_opened.map(|opened| {
417 div()
418 .text_size(px(12.))
419 .text_color(theme::text_soft())
420 .child(opened_label(opened, now))
421 })),
422 )
423 .on_click(cx.listener(move |this, _, window, cx| this.attach_cloud_file(picked.clone(), window, cx)))
424 }
425}
426
427#[cfg(test)]
428mod tests {
429 use chrono::TimeZone as _;
430
431 use super::opened_label;
432
433 #[test]
434 fn opened_reads_like_teams() {
435 let now = chrono::Utc.with_ymd_and_hms(2026, 11, 9, 20, 0, 0).unwrap();
436 let ago = |seconds: i64| opened_label(now - chrono::Duration::seconds(seconds), now);
437 assert_eq!(ago(20), "Opened just now");
438 assert_eq!(ago(60), "Opened 1 minute ago");
439 assert_eq!(ago(4 * 3600 + 100), "Opened 4 hours ago");
440 assert_eq!(ago(6 * 86_400), "Opened 6 days ago");
441 }
442}
crates/app/src/views/composer/rewrite.rs +8 −0
@@ -49,6 +49,14 @@ pub(super) struct RewritePanel {
49 49 _custom_events: Option<Subscription>,
50 50 }
51 51
52 impl RewritePanel {
53 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
54 self.custom_input
55 .as_ref()
56 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
57 }
58 }
59
52 60 struct RewriteResult {
53 61 action: ComposeAction,
54 62 answer: RewriteAnswer,
@@ -49,6 +49,14 @@ pub(super) struct RewritePanel {
49 _custom_events: Option<Subscription>,
49 _custom_events: Option<Subscription>,
50}
50}
51
51
52impl RewritePanel {
53 pub(super) fn input_focused(&self, window: &Window, cx: &App) -> bool {
54 self.custom_input
55 .as_ref()
56 .is_some_and(|input| input.read(cx).focus_handle(cx).is_focused(window))
57 }
58}
59
52struct RewriteResult {
60struct RewriteResult {
53 action: ComposeAction,
61 action: ComposeAction,
54 answer: RewriteAnswer,
62 answer: RewriteAnswer,
crates/core/src/cloud_files.rs added +81 −0
@@ -0,0 +1,81 @@
1 use chatsvc::substrate_search::{QueryRequest, QueryScope, SearchFile, SearchSession};
2 use graph::{CloudFile, FileReference};
3
4 use crate::engine::SyncEngine;
5 use crate::error::{Error, Result};
6 use crate::remote::Remote;
7 use crate::stored::FileKind;
8
9 const RECENT_FETCH: usize = 40;
10 pub const RECENT_SHOWN: usize = 20;
11 const SEARCH_SIZE: usize = 20;
12
13 pub(crate) fn recent_documents(files: Vec<CloudFile>) -> Vec<CloudFile> {
14 files
15 .into_iter()
16 .filter(|file| FileKind::from_name(&file.name).is_document())
17 .take(RECENT_SHOWN)
18 .collect()
19 }
20
21 fn found_file(file: SearchFile) -> Option<CloudFile> {
22 Some(CloudFile {
23 name: file.name,
24 size: file.size.unwrap_or(0),
25 web_url: file.url?,
26 drive_id: None,
27 item_id: None,
28 last_opened: file.modified_at,
29 })
30 }
31
32 impl<R: Remote> SyncEngine<R> {
33 /// The documents Teams lists under "Recent cloud files", newest first.
34 pub async fn recent_cloud_files(&self) -> Result<Vec<CloudFile>> {
35 Ok(recent_documents(self.remote.recent_files(RECENT_FETCH).await?))
36 }
37
38 pub async fn search_cloud_files(&self, search_session: &SearchSession, text: &str) -> Result<Vec<CloudFile>> {
39 let request = QueryRequest {
40 size: SEARCH_SIZE,
41 ..QueryRequest::new(text, QueryScope::Files)
42 };
43 let results = self.server_query(search_session, &request).await?;
44 Ok(results.files.items.into_iter().filter_map(found_file).collect())
45 }
46
47 /// Shares `file` with the chat like an upload; a file the user cannot share still goes out as a link.
48 pub async fn attach_cloud_file(&self, conversation_id: &str, file: &CloudFile) -> Result<FileReference> {
49 let uploaded = self.remote.cloud_file_reference(file).await?;
50 let reference = uploaded
51 .reference()
52 .ok_or_else(|| Error::Unsupported("a cloud file without an eTag"))?;
53 self.share_attachment(conversation_id, &uploaded).await.ok();
54 Ok(reference)
55 }
56 }
57
58 #[cfg(test)]
59 mod tests {
60 use super::*;
61
62 fn file(name: &str) -> CloudFile {
63 CloudFile {
64 name: name.to_owned(),
65 size: 0,
66 web_url: format!("https://x/{name}"),
67 drive_id: None,
68 item_id: None,
69 last_opened: None,
70 }
71 }
72
73 #[test]
74 fn recent_cloud_files_keep_documents_like_teams() {
75 let names: Vec<String> = recent_documents(vec![file("a.pdf"), file("clip.mp4"), file("b.pptx"), file("c.jpg"), file("d.xlsx")])
76 .into_iter()
77 .map(|file| file.name)
78 .collect();
79 assert_eq!(names, ["a.pdf", "b.pptx", "d.xlsx"]);
80 }
81 }
@@ -0,0 +1,81 @@
1use chatsvc::substrate_search::{QueryRequest, QueryScope, SearchFile, SearchSession};
2use graph::{CloudFile, FileReference};
3
4use crate::engine::SyncEngine;
5use crate::error::{Error, Result};
6use crate::remote::Remote;
7use crate::stored::FileKind;
8
9const RECENT_FETCH: usize = 40;
10pub const RECENT_SHOWN: usize = 20;
11const SEARCH_SIZE: usize = 20;
12
13pub(crate) fn recent_documents(files: Vec<CloudFile>) -> Vec<CloudFile> {
14 files
15 .into_iter()
16 .filter(|file| FileKind::from_name(&file.name).is_document())
17 .take(RECENT_SHOWN)
18 .collect()
19}
20
21fn found_file(file: SearchFile) -> Option<CloudFile> {
22 Some(CloudFile {
23 name: file.name,
24 size: file.size.unwrap_or(0),
25 web_url: file.url?,
26 drive_id: None,
27 item_id: None,
28 last_opened: file.modified_at,
29 })
30}
31
32impl<R: Remote> SyncEngine<R> {
33 /// The documents Teams lists under "Recent cloud files", newest first.
34 pub async fn recent_cloud_files(&self) -> Result<Vec<CloudFile>> {
35 Ok(recent_documents(self.remote.recent_files(RECENT_FETCH).await?))
36 }
37
38 pub async fn search_cloud_files(&self, search_session: &SearchSession, text: &str) -> Result<Vec<CloudFile>> {
39 let request = QueryRequest {
40 size: SEARCH_SIZE,
41 ..QueryRequest::new(text, QueryScope::Files)
42 };
43 let results = self.server_query(search_session, &request).await?;
44 Ok(results.files.items.into_iter().filter_map(found_file).collect())
45 }
46
47 /// Shares `file` with the chat like an upload; a file the user cannot share still goes out as a link.
48 pub async fn attach_cloud_file(&self, conversation_id: &str, file: &CloudFile) -> Result<FileReference> {
49 let uploaded = self.remote.cloud_file_reference(file).await?;
50 let reference = uploaded
51 .reference()
52 .ok_or_else(|| Error::Unsupported("a cloud file without an eTag"))?;
53 self.share_attachment(conversation_id, &uploaded).await.ok();
54 Ok(reference)
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 fn file(name: &str) -> CloudFile {
63 CloudFile {
64 name: name.to_owned(),
65 size: 0,
66 web_url: format!("https://x/{name}"),
67 drive_id: None,
68 item_id: None,
69 last_opened: None,
70 }
71 }
72
73 #[test]
74 fn recent_cloud_files_keep_documents_like_teams() {
75 let names: Vec<String> = recent_documents(vec![file("a.pdf"), file("clip.mp4"), file("b.pptx"), file("c.jpg"), file("d.xlsx")])
76 .into_iter()
77 .map(|file| file.name)
78 .collect();
79 assert_eq!(names, ["a.pdf", "b.pptx", "d.xlsx"]);
80 }
81}
crates/core/src/lib.rs +2 −1
@@ -20,6 +20,7 @@ mod channel_sync;
20 20 mod chat_settings_sync;
21 21 mod channel_visibility;
22 22 mod chat_paging;
23 mod cloud_files;
23 24 mod default_reactions;
24 25 mod download;
25 26 mod draft;
@@ -156,7 +157,7 @@ pub use forwarded::{
156 157 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
157 158 };
158 159 pub use graph::{
159 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
160 CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
160 161 MessageExtras, SharedFile, UploadedFile,
161 162 };
162 163 pub use images::StoredImage;
@@ -20,6 +20,7 @@ mod channel_sync;
20mod chat_settings_sync;
20mod chat_settings_sync;
21mod channel_visibility;
21mod channel_visibility;
22mod chat_paging;
22mod chat_paging;
23mod cloud_files;
23mod default_reactions;
24mod default_reactions;
24mod download;
25mod download;
25mod draft;
26mod draft;
@@ -156,7 +157,7 @@ pub use forwarded::{
156 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
157 ForwardInfo, ForwardState, forwarded_texts, forwards, is_forwarded,
157};
158};
158pub use graph::{
159pub use graph::{
159 DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
160 CloudFile, DriveEntry, DriveFolder, FileReference, HostedImage, KeptAttachment, MentionTarget,
160 MessageExtras, SharedFile, UploadedFile,
161 MessageExtras, SharedFile, UploadedFile,
161};
162};
162pub use images::StoredImage;
163pub use images::StoredImage;
crates/core/src/remote.rs +17 −0
@@ -23,6 +23,7 @@ use chatsvc::{
23 23 };
24 24 use chrono::{DateTime, Utc};
25 25 use graph::{
26 CloudFile,
26 27 Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
27 28 OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,
28 29 };
@@ -266,6 +267,14 @@ pub trait Remote {
266 267 Err(Error::Unsupported("sharing a file"))
267 268 }
268 269
270 async fn recent_files(&self, _top: usize) -> Result<Vec<CloudFile>> {
271 Err(Error::Unsupported("recent files"))
272 }
273
274 async fn cloud_file_reference(&self, _file: &CloudFile) -> Result<UploadedFile> {
275 Err(Error::Unsupported("cloud files"))
276 }
277
269 278 async fn delete_file(&self, _file: &UploadedFile) -> Result<()> {
270 279 Err(Error::Unsupported("deleting a file"))
271 280 }
@@ -1093,6 +1102,14 @@ impl Remote for Graph {
1093 1102 Ok(Graph::share_item(self, file, user_ids).await?)
1094 1103 }
1095 1104
1105 async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
1106 Ok(Graph::recent_files(self, top).await?)
1107 }
1108
1109 async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {
1110 Ok(Graph::cloud_file_reference(self, file).await?)
1111 }
1112
1096 1113 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
1097 1114 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
1098 1115 }
@@ -23,6 +23,7 @@ use chatsvc::{
23};
23};
24use chrono::{DateTime, Utc};
24use chrono::{DateTime, Utc};
25use graph::{
25use graph::{
26 CloudFile,
26 Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
27 Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
27 OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,
28 OutgoingMention, Photo, Presence, SharedFile, Tag, Team, UploadDestination, UploadedFile, User,
28};
29};
@@ -266,6 +267,14 @@ pub trait Remote {
266 Err(Error::Unsupported("sharing a file"))
267 Err(Error::Unsupported("sharing a file"))
267 }
268 }
268
269
270 async fn recent_files(&self, _top: usize) -> Result<Vec<CloudFile>> {
271 Err(Error::Unsupported("recent files"))
272 }
273
274 async fn cloud_file_reference(&self, _file: &CloudFile) -> Result<UploadedFile> {
275 Err(Error::Unsupported("cloud files"))
276 }
277
269 async fn delete_file(&self, _file: &UploadedFile) -> Result<()> {
278 async fn delete_file(&self, _file: &UploadedFile) -> Result<()> {
270 Err(Error::Unsupported("deleting a file"))
279 Err(Error::Unsupported("deleting a file"))
271 }
280 }
@@ -1093,6 +1102,14 @@ impl Remote for Graph {
1093 Ok(Graph::share_item(self, file, user_ids).await?)
1102 Ok(Graph::share_item(self, file, user_ids).await?)
1094 }
1103 }
1095
1104
1105 async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
1106 Ok(Graph::recent_files(self, top).await?)
1107 }
1108
1109 async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {
1110 Ok(Graph::cloud_file_reference(self, file).await?)
1111 }
1112
1096 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
1113 async fn delete_file(&self, file: &UploadedFile) -> Result<()> {
1097 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
1114 Ok(Graph::delete_drive_item(self, &file.drive_id, &file.item_id).await?)
1098 }
1115 }
crates/graph/examples/recent_files_probe.rs added +19 −0
@@ -0,0 +1,19 @@
1 use graph::Graph;
2 use session::{DEFAULT_ENDPOINT, Session};
3
4 #[tokio::main]
5 async fn main() {
6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7 let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));
8 let files = graph.recent_files(40).await.expect("recent files");
9 println!("recent {}", files.len());
10 for file in files.iter().take(12) {
11 println!(" {} opened {:?} ids {}", file.name, file.last_opened, file.item_id.is_some());
12 }
13 if let Some(first) = files.first() {
14 match graph.cloud_file_reference(first).await {
15 Ok(uploaded) => println!("reference ok: {} etag {}", uploaded.name, uploaded.reference().is_some()),
16 Err(error) => println!("reference error: {error}"),
17 }
18 }
19 }
@@ -0,0 +1,19 @@
1use graph::Graph;
2use session::{DEFAULT_ENDPOINT, Session};
3
4#[tokio::main]
5async fn main() {
6 let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
7 let graph = Graph::new(Session::connect(&endpoint).await.expect("browser"));
8 let files = graph.recent_files(40).await.expect("recent files");
9 println!("recent {}", files.len());
10 for file in files.iter().take(12) {
11 println!(" {} opened {:?} ids {}", file.name, file.last_opened, file.item_id.is_some());
12 }
13 if let Some(first) = files.first() {
14 match graph.cloud_file_reference(first).await {
15 Ok(uploaded) => println!("reference ok: {} etag {}", uploaded.name, uploaded.reference().is_some()),
16 Err(error) => println!("reference error: {error}"),
17 }
18 }
19}
crates/graph/src/cloud_files.rs added +98 −0
@@ -0,0 +1,98 @@
1 use chrono::{DateTime, Utc};
2 use serde_json::Value;
3 use session::{Method, Scope};
4
5 use crate::client::Graph;
6 use crate::error::Result;
7 use crate::files::{FILES_SCOPE, UploadedFile, finished_item, share_id};
8 use crate::urls;
9
10 /// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again.
11 #[derive(Debug, Clone, PartialEq, Eq)]
12 pub struct CloudFile {
13 pub name: String,
14 pub size: u64,
15 pub web_url: String,
16 pub drive_id: Option<String>,
17 pub item_id: Option<String>,
18 pub last_opened: Option<DateTime<Utc>>,
19 }
20
21 fn time(value: &Value) -> Option<DateTime<Utc>> {
22 DateTime::parse_from_rfc3339(value.as_str()?)
23 .ok()
24 .map(|time| time.with_timezone(&Utc))
25 }
26
27 fn recent_file(item: &Value) -> Option<CloudFile> {
28 let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);
29 item.get("file")?;
30 let opened = |source: &Value| time(&source["fileSystemInfo"]["lastAccessedDateTime"]);
31 Some(CloudFile {
32 name: item["name"].as_str()?.to_owned(),
33 size: item["size"].as_u64().or_else(|| remote["size"].as_u64()).unwrap_or(0),
34 web_url: item["webUrl"].as_str().or_else(|| remote["webUrl"].as_str())?.to_owned(),
35 drive_id: remote["parentReference"]["driveId"].as_str().map(str::to_owned),
36 item_id: remote["id"].as_str().map(str::to_owned),
37 last_opened: opened(remote).or_else(|| opened(item)),
38 })
39 }
40
41 pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {
42 body["value"]
43 .as_array()
44 .into_iter()
45 .flatten()
46 .filter_map(recent_file)
47 .collect()
48 }
49
50 impl Graph {
51 pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
52 let answer = self
53 .session()
54 .request(Method::Get, &urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE), None)
55 .await?;
56 Ok(parse_recent_files(&answer.body))
57 }
58
59 /// The reference a message needs to carry `file`: its drive item, found by id or else by its link.
60 pub async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {
61 let url = match (&file.drive_id, &file.item_id) {
62 (Some(drive_id), Some(item_id)) => urls::drive_item(drive_id, item_id),
63 _ => urls::shared_drive_item(&share_id(&file.web_url)),
64 };
65 let answer = self
66 .session()
67 .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None)
68 .await?;
69 finished_item(answer.body)
70 }
71 }
72
73 #[cfg(test)]
74 mod tests {
75 use serde_json::json;
76
77 use super::*;
78
79 #[test]
80 fn recent_files_take_ids_and_open_time_from_the_remote_item() {
81 let body = json!({"value": [
82 {"name": "plan.pdf", "size": 12, "webUrl": "https://x/plan.pdf", "file": {},
83 "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T10:00:00Z"},
84 "remoteItem": {"id": "item-1", "parentReference": {"driveId": "drive-1"},
85 "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T12:00:00Z"}}},
86 {"name": "Folder", "webUrl": "https://x/folder", "folder": {}},
87 {"name": "notes.docx", "webUrl": "https://x/notes.docx", "file": {}, "id": "item-2",
88 "parentReference": {"driveId": "drive-2"}}
89 ]});
90 let files = parse_recent_files(&body);
91 assert_eq!(files.len(), 2);
92 assert_eq!(files[0].item_id.as_deref(), Some("item-1"));
93 assert_eq!(files[0].drive_id.as_deref(), Some("drive-1"));
94 assert_eq!(files[0].last_opened.unwrap().to_rfc3339(), "2026-11-09T12:00:00+00:00");
95 assert_eq!((files[1].item_id.as_deref(), files[1].size), (Some("item-2"), 0));
96 assert!(files[1].last_opened.is_none());
97 }
98 }
@@ -0,0 +1,98 @@
1use chrono::{DateTime, Utc};
2use serde_json::Value;
3use session::{Method, Scope};
4
5use crate::client::Graph;
6use crate::error::Result;
7use crate::files::{FILES_SCOPE, UploadedFile, finished_item, share_id};
8use crate::urls;
9
10/// A file in OneDrive or SharePoint that can be attached by reference, without uploading it again.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct CloudFile {
13 pub name: String,
14 pub size: u64,
15 pub web_url: String,
16 pub drive_id: Option<String>,
17 pub item_id: Option<String>,
18 pub last_opened: Option<DateTime<Utc>>,
19}
20
21fn time(value: &Value) -> Option<DateTime<Utc>> {
22 DateTime::parse_from_rfc3339(value.as_str()?)
23 .ok()
24 .map(|time| time.with_timezone(&Utc))
25}
26
27fn recent_file(item: &Value) -> Option<CloudFile> {
28 let remote = item.get("remoteItem").filter(|remote| remote.is_object()).unwrap_or(item);
29 item.get("file")?;
30 let opened = |source: &Value| time(&source["fileSystemInfo"]["lastAccessedDateTime"]);
31 Some(CloudFile {
32 name: item["name"].as_str()?.to_owned(),
33 size: item["size"].as_u64().or_else(|| remote["size"].as_u64()).unwrap_or(0),
34 web_url: item["webUrl"].as_str().or_else(|| remote["webUrl"].as_str())?.to_owned(),
35 drive_id: remote["parentReference"]["driveId"].as_str().map(str::to_owned),
36 item_id: remote["id"].as_str().map(str::to_owned),
37 last_opened: opened(remote).or_else(|| opened(item)),
38 })
39}
40
41pub fn parse_recent_files(body: &Value) -> Vec<CloudFile> {
42 body["value"]
43 .as_array()
44 .into_iter()
45 .flatten()
46 .filter_map(recent_file)
47 .collect()
48}
49
50impl Graph {
51 pub async fn recent_files(&self, top: usize) -> Result<Vec<CloudFile>> {
52 let answer = self
53 .session()
54 .request(Method::Get, &urls::recent_drive_items(top), &Scope::graph(FILES_SCOPE), None)
55 .await?;
56 Ok(parse_recent_files(&answer.body))
57 }
58
59 /// The reference a message needs to carry `file`: its drive item, found by id or else by its link.
60 pub async fn cloud_file_reference(&self, file: &CloudFile) -> Result<UploadedFile> {
61 let url = match (&file.drive_id, &file.item_id) {
62 (Some(drive_id), Some(item_id)) => urls::drive_item(drive_id, item_id),
63 _ => urls::shared_drive_item(&share_id(&file.web_url)),
64 };
65 let answer = self
66 .session()
67 .request(Method::Get, &url, &Scope::graph(FILES_SCOPE), None)
68 .await?;
69 finished_item(answer.body)
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use serde_json::json;
76
77 use super::*;
78
79 #[test]
80 fn recent_files_take_ids_and_open_time_from_the_remote_item() {
81 let body = json!({"value": [
82 {"name": "plan.pdf", "size": 12, "webUrl": "https://x/plan.pdf", "file": {},
83 "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T10:00:00Z"},
84 "remoteItem": {"id": "item-1", "parentReference": {"driveId": "drive-1"},
85 "fileSystemInfo": {"lastAccessedDateTime": "2026-11-09T12:00:00Z"}}},
86 {"name": "Folder", "webUrl": "https://x/folder", "folder": {}},
87 {"name": "notes.docx", "webUrl": "https://x/notes.docx", "file": {}, "id": "item-2",
88 "parentReference": {"driveId": "drive-2"}}
89 ]});
90 let files = parse_recent_files(&body);
91 assert_eq!(files.len(), 2);
92 assert_eq!(files[0].item_id.as_deref(), Some("item-1"));
93 assert_eq!(files[0].drive_id.as_deref(), Some("drive-1"));
94 assert_eq!(files[0].last_opened.unwrap().to_rfc3339(), "2026-11-09T12:00:00+00:00");
95 assert_eq!((files[1].item_id.as_deref(), files[1].size), (Some("item-2"), 0));
96 assert!(files[1].last_opened.is_none());
97 }
98}
crates/graph/src/files.rs +1 −1
@@ -443,7 +443,7 @@ impl Graph {
443 443 }
444 444 }
445 445
446 fn finished_item(body: Value) -> Result<UploadedFile> {
446 pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
447 447 let item: DriveItem = serde_json::from_value(body)?;
448 448 let drive_id = item
449 449 .drive_id()
@@ -443,7 +443,7 @@ impl Graph {
443 }
443 }
444}
444}
445
445
446fn finished_item(body: Value) -> Result<UploadedFile> {
446pub(crate) fn finished_item(body: Value) -> Result<UploadedFile> {
447 let item: DriveItem = serde_json::from_value(body)?;
447 let item: DriveItem = serde_json::from_value(body)?;
448 let drive_id = item
448 let drive_id = item
449 .drive_id()
449 .drive_id()
crates/graph/src/lib.rs +2 −0
@@ -1,4 +1,5 @@
1 1 mod client;
2 mod cloud_files;
2 3 mod content;
3 4 mod error;
4 5 mod files;
@@ -13,6 +14,7 @@ mod target;
13 14 mod urls;
14 15 mod writes;
15 16
17 pub use cloud_files::CloudFile;
16 18 pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
17 19 pub use error::{Error, Result};
18 20 pub use files::{
@@ -1,4 +1,5 @@
1mod client;
1mod client;
2mod cloud_files;
2mod content;
3mod content;
3mod error;
4mod error;
4mod files;
5mod files;
@@ -13,6 +14,7 @@ mod target;
13mod urls;
14mod urls;
14mod writes;
15mod writes;
15
16
17pub use cloud_files::CloudFile;
16pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
18pub use client::{BATCH_SIZE, CHAT_PAGE_SIZE, Graph, MESSAGE_PAGE_SIZE};
17pub use error::{Error, Result};
19pub use error::{Error, Result};
18pub use files::{
20pub use files::{
crates/graph/src/urls.rs +4 −0
@@ -231,6 +231,10 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
231 231 )
232 232 }
233 233
234 pub fn recent_drive_items(top: usize) -> String {
235 format!("{GRAPH}/v1.0/me/drive/recent?$top={top}")
236 }
237
234 238 pub fn shared_drive_item(share_id: &str) -> String {
235 239 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
236 240 }
@@ -231,6 +231,10 @@ pub fn drive_item(drive_id: &str, item_id: &str) -> String {
231 )
231 )
232}
232}
233
233
234pub fn recent_drive_items(top: usize) -> String {
235 format!("{GRAPH}/v1.0/me/drive/recent?$top={top}")
236}
237
234pub fn shared_drive_item(share_id: &str) -> String {
238pub fn shared_drive_item(share_id: &str) -> String {
235 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
239 format!("{GRAPH}/v1.0/shares/{}/driveItem", segment(share_id))
236}
240}