BlueGit

ict rusty-teams

Files

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

conversation.rs

e7ea3d7f History
conversation.rs 147.9 KiB Download Raw
1use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5use std::time::{Duration, Instant};
6
7use chrono::{DateTime, Local, Offset, Utc};
8use gpui_kit::assets::IconName;
9use gpui_kit::component::{
10 button::{Button, ButtonVariants as _},
11 h_flex,
12 input::{Escape, InputState},
13 message_scroller::{MessageScroller, MessageScrollerState},
14 tooltip::Tooltip,
15 v_flex,
16};
17use gpui_kit::prelude::FluentBuilder as _;
18use gpui_kit::*;
19use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id};
20use teams_core::{
21 ExecuteAction, FileCard, JumpPlan, LinkPreview, WindowDirection, without_islands,
22};
23
24mod channel_details;
25pub use channel_details::{
26 CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG,
27 CHANNEL_DETAILS_TAG,
28};
29mod deletes;
30mod detached;
31mod feed;
32mod forward_select;
33#[cfg(test)]
34pub use forward_select::{
35 FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG,
36};
37mod jump;
38mod pins;
39mod proposal;
40mod recap;
41mod receipt_fade;
42mod render_env;
43mod scheduled;
44mod shared;
45
46use super::add_people_dialog::open_add_people;
47use super::attachments::FileActions;
48use super::avatar::{
49 bot_tile, member_stack, person_avatar, spec_avatar, square_avatar, with_presence,
50};
51use super::call_controls::header_call_controls;
52use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH};
53use super::chat_members::members_popover;
54use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
55use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent};
56use super::group_name::group_name_button;
57use super::message_actions::{Action, DelegateEntry, MessageMenu};
58use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
59use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder};
60use super::pin_banner::{pin_banner_inset, pin_banner_overlay};
61use super::post_card::render_post;
62use super::profile_card::opens_profile;
63use super::reaction_picker::{PickHandler, ReactionPicker};
64use super::reaction_pills::{ReactionControls, ReactionPopover};
65use super::scroll_edge::edge_divider;
66use super::toolbar_placement::{TimelineBounds, record_bounds};
67use super::widgets::{icon, symbol};
68use crate::agents::{AgentRun, StartRequest};
69use crate::app_state::{AppEvent, AppState, Selection, composer_name, selection_title};
70use crate::backend::Engine;
71use crate::card_state::CardScope;
72use crate::channel_files::DownloadSource;
73use crate::chat_settings_actions::shown_receipt;
74use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others};
75use crate::demo_library::DemoLibrary;
76use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
77use crate::emoji;
78use crate::emoticons;
79use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
80use crate::notice::short_error;
81use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
82use crate::pending_rows::pending_row;
83use crate::people::{local_names, resolve_names};
84use crate::reaction_model::UNKNOWN_REACTOR;
85use crate::read_state::{ReadTrigger, plan_read};
86use crate::rows::{
87 Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
88 apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
89 forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph,
90 place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction,
91 thread_list_rows, thread_rows,
92};
93use crate::runtime;
94use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
95use crate::sidebar_model::{AvatarSpec, Face, channel_unread};
96use crate::theme;
97use crate::translation::TranslationLine;
98use crate::typing::typing_tooltip;
99use app_ui_kit::layout::{ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH};
100use detached::DetachedWindow;
101use feed::{FeedStash, subject_input};
102use mcp::ReactionProposal;
103use render_env::RenderEnv;
104use shared::SharedState;
105
106pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
107pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
108pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
109pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
110const HEADER_HEIGHT: f32 = 60.;
111const HEADER_PADDING: f32 = 20.;
112const HEADER_GAP: f32 = 12.;
113const HEADER_LEAD_SIZE: f32 = 36.;
114const TABS_INLINE_MIN_WIDTH: f32 = 560.;
115const FIND_MIN_TIMELINE_WIDTH: f32 = 360.;
116const TABS_ROW_HEIGHT: f32 = 36.;
117const CHAT_OPEN_LIMIT: usize = 60;
118const CHANNEL_OPEN_LIMIT: usize = 300;
119const GROWTH_HEADROOM: usize = 20;
120const META_USER_ID: &str = "me_user_id";
121const PENDING_KEY_PREFIX: &str = "pending-";
122const DEMO_DOWNLOAD_STEPS: u8 = 10;
123const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100);
124const JUMP_SCAN_LIMIT: usize = 5000;
125const JUMP_CONTEXT_MESSAGES: usize = 12;
126const HIGHLIGHT_DURATION: Duration = Duration::from_secs(2);
127const PROGRESS_DELAY: Duration = Duration::from_millis(400);
128const SLOW_AFTER: Duration = Duration::from_secs(8);
129const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500);
130const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400);
131const PROGRESS_BAR_WIDTH: f32 = 0.35;
132const TYPING_LINE_HEIGHT: f32 = 22.;
133const TYPING_DOT_SIZE: f32 = 5.;
134const TYPING_DOT_COUNT: usize = 3;
135const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200);
136
137#[derive(Clone, Copy)]
138enum HoverSlot {
139 Row,
140 Toolbar,
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
144enum ViewMode {
145 Flat,
146 ThreadList,
147 Thread(String),
148}
149
150#[derive(Default)]
151struct SyncProgress {
152 messages: bool,
153 receipts: bool,
154 empty_cache: bool,
155 newest_cached: Option<DateTime<Utc>>,
156 shown_at: Option<Instant>,
157 slow: bool,
158 failed: bool,
159}
160
161impl SyncProgress {
162 fn running(&self) -> bool {
163 self.messages || self.receipts
164 }
165}
166
167struct Current {
168 selection: Selection,
169 title: String,
170 mode: ViewMode,
171 loaded_limit: usize,
172 loaded_count: usize,
173 has_older: bool,
174 loading_older: bool,
175 older_blocked: bool,
176 fetched: bool,
177 first_unread: Option<String>,
178 sync: SyncProgress,
179 detached: Option<DetachedWindow>,
180 window_request: Option<String>,
181}
182
183struct ReactionDetails {
184 message_key: String,
185 anchor_glyph: String,
186 tab: Option<String>,
187}
188
189#[derive(Clone, Copy, PartialEq, Eq)]
190enum ReactionAttempt {
191 Acted,
192 Started,
193 AlreadyThere,
194 MissingMessage,
195 Blocked,
196}
197
198pub struct ConversationView {
199 app: Entity<AppState>,
200 pinned: bool,
201 scroller: Entity<MessageScrollerState>,
202 composer: Entity<Composer>,
203 subject: Entity<InputState>,
204 new_post_open: bool,
205 reply_composer: Option<Entity<Composer>>,
206 reply_root: Option<String>,
207 feed_stash: Option<FeedStash>,
208 feed_rows_seen: Rc<Cell<usize>>,
209 feed_at_top: bool,
210 draft: Entity<NewChatDraft>,
211 draft_active: bool,
212 draft_created: Option<(Vec<String>, String)>,
213 draft_error: Option<String>,
214 rows: Rc<RefCell<Vec<Row>>>,
215 current: Option<Current>,
216 pending: Vec<MessageRow>,
217 pending_counter: usize,
218 pending_outgoing: HashMap<String, Outgoing>,
219 pending_reactions: PendingReactions,
220 downloads: Downloads,
221 hovered_message: Option<String>,
222 toolbar_hovered: Option<String>,
223 timeline_bounds: TimelineBounds,
224 header_width: Rc<Cell<f32>>,
225 toolbar_pinned: Option<String>,
226 toolbar_suppressed: Option<String>,
227 recent: Entity<emoji::Recent>,
228 picker: Entity<ReactionPicker>,
229 reaction_details: Option<ReactionDetails>,
230 highlighted_message: Option<String>,
231 pin_index: usize,
232 channel_details_open: bool,
233 pinned_posts_expanded: bool,
234 channel_details_scroll: ScrollHandle,
235 scroller_watch: Option<(EntityId, Subscription)>,
236 pin_previews: HashMap<String, pins::PinPreview>,
237 pin_fetches: HashSet<String>,
238 notice: Option<String>,
239 scheduled_failure: Option<scheduled::ScheduledFailure>,
240 scheduled_in_flight: HashSet<String>,
241 drag_file_count: usize,
242 sync_generation: u64,
243 window_active: bool,
244 pane: ChannelPane,
245 recap: recap::RecapState,
246 recap_search: Entity<InputState>,
247 channel_tabs: Vec<ChannelTabRecord>,
248 tab_links: HashMap<String, String>,
249 focus_handle: FocusHandle,
250 shared: SharedState,
251 demo_library: DemoLibrary,
252 new_folder_input: Option<Entity<InputState>>,
253 agent_layouts: HashMap<String, (usize, bool)>,
254 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
255 reaction_proposals: Rc<RefCell<HashMap<String, ReactionProposal>>>,
256 receipt_fade: receipt_fade::ReceiptFade,
257 find_panel: Option<Entity<FindPanel>>,
258 find_subscription: Option<Subscription>,
259 _subscriptions: Vec<Subscription>,
260}
261
262fn open_limit(selection: &Selection) -> usize {
263 match selection {
264 Selection::Chat(_) => CHAT_OPEN_LIMIT,
265 Selection::Channel(_) => CHANNEL_OPEN_LIMIT,
266 }
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Eq)]
270enum DropTarget {
271 Chat,
272 Channel,
273 Library,
274 NewChat,
275}
276
277fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) {
278 let files = if count == 1 {
279 "1 file".to_owned()
280 } else {
281 format!("{count} files")
282 };
283 match target {
284 DropTarget::Chat => (
285 format!("Drop to attach to {title}"),
286 format!("{files}. Images go into the message, other files to your OneDrive."),
287 ),
288 DropTarget::Channel => (
289 format!("Drop to attach to {title}"),
290 format!("{files}. Images go into the message, other files to the channel's Files."),
291 ),
292 DropTarget::Library => (
293 format!("Drop to upload to {title}"),
294 format!("{files}. Files go into the folder you have open."),
295 ),
296 DropTarget::NewChat => (
297 "Drop to attach to the new chat".to_owned(),
298 format!(
299 "{files}. Images go into the message. Files can be added once the chat exists."
300 ),
301 ),
302 }
303}
304
305fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool {
306 match mode {
307 ViewMode::Flat => record.target == OutboxTarget::Flat,
308 ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread),
309 ViewMode::Thread(root_id) => {
310 record.target == OutboxTarget::Thread
311 && record.thread_root_id.as_deref() == Some(root_id.as_str())
312 }
313 }
314}
315
316enum DownloadEvent {
317 Progress(u8),
318 Finished(Result<PathBuf, String>),
319}
320
321async fn save_file(
322 engine: &Engine,
323 card: &FileCard,
324 source: &DownloadSource,
325 events: &tokio::sync::mpsc::UnboundedSender<DownloadEvent>,
326) -> Result<PathBuf, String> {
327 let mut part = PartFile::create(&downloads::downloads_directory(), &card.name)
328 .map_err(|error| short_error(&error))?;
329 let write = |bytes: &[u8]| part.write(bytes);
330 let progress = |percent| {
331 let _ = events.send(DownloadEvent::Progress(percent));
332 };
333 match source {
334 DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await,
335 DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await,
336 }
337 .map_err(|error| short_error(&error))?;
338 part.finish().map_err(|error| short_error(&error))
339}
340
341impl ConversationView {
342 fn file_actions(
343 &self,
344 message_key: &str,
345 files: &[FileCard],
346 view: WeakEntity<Self>,
347 ) -> FileActions {
348 let conversation_id = self.conversation_id().unwrap_or_default();
349 let (key, cards) = (message_key.to_owned(), files.to_vec());
350 let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect();
351 FileActions {
352 states: self
353 .downloads
354 .states_for(&conversation_id, message_key, &open_urls),
355 activate: Rc::new(move |index, cx| {
356 let Some(card) = cards.get(index).cloned() else {
357 return;
358 };
359 let key = key.clone();
360 let conversation_id = conversation_id.clone();
361 view.update(cx, |this, cx| {
362 this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx)
363 })
364 .ok();
365 }),
366 }
367 }
368
369 fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
370 let Some(current) = self.current.as_ref() else {
371 return;
372 };
373 let now = Local::now();
374 let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
375 let Some(index) = position_of(&items, message_key, url) else {
376 return;
377 };
378 let request = ViewerRequest {
379 conversation_id: current.selection.conversation_id().to_owned(),
380 conversation_title: selection_title(&self.app.read(cx).sidebar, &current.selection),
381 items,
382 index,
383 };
384 self.app
385 .update(cx, |state, cx| state.request_image_viewer(request, cx));
386 }
387
388 fn activate_file(
389 &mut self,
390 conversation_id: &str,
391 message_key: &str,
392 card: FileCard,
393 source: DownloadSource,
394 cx: &mut Context<Self>,
395 ) {
396 let key = DownloadKey::new(conversation_id, message_key, &card.open_url);
397 match downloads::click_action(self.downloads.state(&key)) {
398 ClickAction::Ignore => {}
399 ClickAction::Start => self.start_download(key, card, source, cx),
400 ClickAction::Reveal(path) => {
401 let folder = path
402 .parent()
403 .map(Path::to_path_buf)
404 .unwrap_or_else(downloads::downloads_directory);
405 match downloads::reveal_target(&path, path.exists(), folder) {
406 RevealTarget::File(path) => downloads::reveal_in_file_manager(&path),
407 RevealTarget::Folder(folder) => cx.open_with_system(&folder),
408 }
409 }
410 }
411 }
412
413 fn start_download(
414 &mut self,
415 key: DownloadKey,
416 card: FileCard,
417 source: DownloadSource,
418 cx: &mut Context<Self>,
419 ) {
420 if !self.downloads.begin(&key) {
421 return;
422 }
423 cx.notify();
424 let state = self.app.read(cx);
425 let (demo, engine) = (state.mode.demo, state.engine.clone());
426 let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<DownloadEvent>();
427 if demo {
428 cx.spawn(async move |this, cx| {
429 for step in 1..=DEMO_DOWNLOAD_STEPS {
430 cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await;
431 let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8;
432 let progressed = this.update(cx, |this, cx| {
433 this.downloads.set_progress(&key, percent);
434 cx.notify();
435 });
436 if progressed.is_err() {
437 return;
438 }
439 }
440 let outcome =
441 downloads::write_demo_file(&card.name).map_err(|error| short_error(&error));
442 this.update(cx, |this, cx| {
443 this.downloads.finish(&key, outcome);
444 cx.notify();
445 })
446 .ok();
447 })
448 .detach();
449 return;
450 }
451 let Some(engine) = engine else {
452 self.downloads.finish(&key, Err("not connected".to_owned()));
453 return;
454 };
455 drop(runtime::spawn(async move {
456 let outcome = save_file(&engine, &card, &source, &sender).await;
457 let _ = sender.send(DownloadEvent::Finished(outcome));
458 }));
459 cx.spawn(async move |this, cx| {
460 while let Some(event) = receiver.recv().await {
461 let updated = this.update(cx, |this, cx| {
462 match event {
463 DownloadEvent::Progress(percent) => {
464 this.downloads.set_progress(&key, percent)
465 }
466 DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome),
467 }
468 cx.notify();
469 });
470 if updated.is_err() {
471 break;
472 }
473 }
474 })
475 .detach();
476 }
477
478 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
479 Self::build(app, None, window, cx)
480 }
481
482 pub fn timeline_bounds(&self) -> TimelineBounds {
483 self.timeline_bounds.clone()
484 }
485
486 pub fn pinned_to(
487 app: Entity<AppState>,
488 selection: Selection,
489 window: &mut Window,
490 cx: &mut Context<Self>,
491 ) -> Self {
492 Self::build(app, Some(selection), window, cx)
493 }
494
495 fn build(
496 app: Entity<AppState>,
497 pinned: Option<Selection>,
498 window: &mut Window,
499 cx: &mut Context<Self>,
500 ) -> Self {
501 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
502 let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
503 let subject = subject_input(window, cx);
504 let recap_search = recap::search_input(window, cx);
505 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
506 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
507 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
508 let mut subscriptions = vec![
509 cx.subscribe_in(&app, window, Self::on_app_event),
510 cx.observe(&app, |_, _, cx| cx.notify()),
511 cx.subscribe_in(&composer, window, Self::on_composer_event),
512 cx.subscribe_in(&draft, window, Self::on_draft_event),
513 cx.subscribe_in(&subject, window, Self::on_subject_event),
514 cx.subscribe_in(&recap_search, window, Self::on_recap_search_event),
515 cx.observe_window_activation(window, Self::on_window_activation),
516 cx.on_app_quit(|this, cx| {
517 this.composer
518 .update(cx, |composer, cx| composer.save_draft_now(cx));
519 async {}
520 }),
521 cx.observe_keystrokes(|this, event, _, cx| {
522 if event.keystroke.key == "escape" {
523 this.close_reaction_details(cx);
524 }
525 }),
526 ];
527 if let Some(runs) = crate::agents::runs_handle(cx) {
528 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
529 }
530 if let Some(api) = crate::agent_api::handle(cx) {
531 subscriptions.push(cx.observe(&api, |this, _, cx| this.sync_reaction_pills(cx)));
532 }
533 let mut view = ConversationView {
534 app,
535 pinned: pinned.is_some(),
536 scroller,
537 composer,
538 subject,
539 new_post_open: false,
540 reply_composer: None,
541 reply_root: None,
542 feed_stash: None,
543 feed_rows_seen: Rc::new(Cell::new(usize::MAX)),
544 feed_at_top: true,
545 draft,
546 draft_active: false,
547 draft_created: None,
548 draft_error: None,
549 rows: Rc::new(RefCell::new(Vec::new())),
550 current: None,
551 pending: Vec::new(),
552 pending_counter: 0,
553 pending_outgoing: HashMap::new(),
554 pending_reactions: HashMap::new(),
555 downloads: Downloads::default(),
556 hovered_message: None,
557 toolbar_hovered: None,
558 timeline_bounds: TimelineBounds::default(),
559 header_width: Rc::default(),
560 toolbar_pinned: None,
561 toolbar_suppressed: None,
562 recent,
563 picker,
564 reaction_details: None,
565 highlighted_message: None,
566 pin_index: 0,
567 channel_details_open: false,
568 pinned_posts_expanded: false,
569 channel_details_scroll: ScrollHandle::new(),
570 scroller_watch: None,
571 pin_previews: HashMap::new(),
572 pin_fetches: HashSet::new(),
573 notice: None,
574 scheduled_failure: None,
575 scheduled_in_flight: HashSet::new(),
576 drag_file_count: 0,
577 sync_generation: 0,
578 window_active: window.is_window_active(),
579 pane: ChannelPane::Posts,
580 recap: recap::RecapState::default(),
581 recap_search,
582 channel_tabs: Vec::new(),
583 tab_links: HashMap::new(),
584 focus_handle: cx.focus_handle(),
585 shared: SharedState::default(),
586 demo_library: DemoLibrary::default(),
587 new_folder_input: None,
588 agent_layouts: HashMap::new(),
589 agent_runs: Rc::new(RefCell::new(HashMap::new())),
590 reaction_proposals: Rc::new(RefCell::new(HashMap::new())),
591 receipt_fade: receipt_fade::ReceiptFade::default(),
592 find_panel: None,
593 find_subscription: None,
594 _subscriptions: subscriptions,
595 };
596 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
597 view.open(selection, window, cx);
598 }
599 view
600 }
601
602 #[cfg_attr(not(windows), allow(dead_code))]
603 pub fn composer_is_empty(&self, cx: &App) -> bool {
604 self.composer.read(cx).is_empty(cx)
605 }
606
607 #[cfg_attr(not(windows), allow(dead_code))]
608 pub fn send_in_flight(&self) -> bool {
609 self.pending
610 .iter()
611 .any(|row| matches!(row.delivery, Delivery::Sending))
612 }
613
614 fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context<Self>) {
615 self.window_active = window.is_window_active();
616 self.mark_read(ReadTrigger::Activation, cx);
617 }
618
619 fn on_app_event(
620 &mut self,
621 _: &Entity<AppState>,
622 event: &AppEvent,
623 window: &mut Window,
624 cx: &mut Context<Self>,
625 ) {
626 match event {
627 AppEvent::Selection if self.pinned => {}
628 AppEvent::Selection => {
629 self.reaction_details = None;
630 let (new_chat, selection) = {
631 let state = self.app.read(cx);
632 (state.new_chat, state.selection.clone())
633 };
634 if new_chat {
635 self.enter_draft(window, cx);
636 return;
637 }
638 if self.draft_active {
639 let created = self
640 .draft_created
641 .as_ref()
642 .map(|(_, chat_id)| chat_id.clone());
643 if let Some(chat_id) = created {
644 self.composer
645 .update(cx, |composer, _| composer.carry_images_into(chat_id));
646 }
647 self.leave_draft(window, cx);
648 }
649 match selection {
650 Some(selection) => self.open(selection, window, cx),
651 None => {
652 self.current = None;
653 self.rebuild(true, cx);
654 }
655 }
656 }
657 AppEvent::Messages(conversation_id) => {
658 let is_current = self
659 .current
660 .as_ref()
661 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
662 if is_current {
663 if self.shared_active() || self.recap_active() || self.channel_details_open {
664 self.refresh_shared_items(cx);
665 }
666 self.rebuild(false, cx);
667 self.mark_read(ReadTrigger::Incoming, cx);
668 self.on_pins_changed(conversation_id, cx);
669 }
670 }
671 AppEvent::Images(keys) => self.remeasure_images(keys, cx),
672 AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx),
673 AppEvent::Jump => self.apply_pending_jump(cx),
674 AppEvent::Status => {
675 if let Some(current) = self.current.as_mut()
676 && current.sync.failed
677 {
678 current.fetched = false;
679 }
680 self.start_fetch(cx)
681 }
682 AppEvent::Directory => {
683 self.refresh_reactor_names(cx);
684 cx.notify();
685 }
686 AppEvent::ForwardSelection => self.on_forward_selection_changed(window, cx),
687 AppEvent::TaskDialog
688 | AppEvent::LocalPreviews
689 | AppEvent::Forward
690 | AppEvent::ImageViewer
691 | AppEvent::StatusMessage
692 | AppEvent::Settings(_)
693 | AppEvent::Profile
694 | AppEvent::CallHistory
695 | AppEvent::Ring
696 | AppEvent::MissedCall(_)
697 | AppEvent::MeetingReminder
698 | AppEvent::MeetingChime
699 | AppEvent::CallTone(_)
700 | AppEvent::SoundSettings
701 | AppEvent::Call => {}
702 AppEvent::LiveMeeting => cx.notify(),
703 AppEvent::Saved => cx.notify(),
704 AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx),
705 AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx),
706 AppEvent::Typing => cx.notify(),
707 AppEvent::Scheduled => self.rebuild(false, cx),
708 AppEvent::Outbox(conversation_id) => {
709 let is_current = self
710 .current
711 .as_ref()
712 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
713 if is_current {
714 self.reload_pending(cx);
715 self.rebuild(false, cx);
716 }
717 }
718 AppEvent::Sidebar => {
719 self.reload_channel_tabs(cx);
720 self.mark_read(ReadTrigger::Incoming, cx);
721 self.refresh_reactor_names(cx);
722 if self.draft_active {
723 self.on_draft_changed(window, cx);
724 } else if let Some(current) = self.current.as_mut() {
725 let title = selection_title(&self.app.read(cx).sidebar, &current.selection);
726 if current.title != title {
727 current.title = title;
728 let conversation_id = current.selection.conversation_id().to_owned();
729 let name = composer_name(&self.app.read(cx).sidebar, &current.selection);
730 self.composer.update(cx, |composer, cx| {
731 composer.set_conversation(&conversation_id, &name, window, cx)
732 });
733 cx.notify();
734 }
735 }
736 }
737 }
738 }
739
740 fn on_composer_event(
741 &mut self,
742 _: &Entity<Composer>,
743 event: &ComposerEvent,
744 window: &mut Window,
745 cx: &mut Context<Self>,
746 ) {
747 self.report_composer_activity(event, cx);
748 match event {
749 ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx),
750 ComposerEvent::Schedule { outgoing, send_at } => {
751 self.schedule((**outgoing).clone(), *send_at, window, cx)
752 }
753 ComposerEvent::EditLast => self.edit_last_own(window, cx),
754 ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx),
755 ComposerEvent::Typing(active) => self.send_typing(*active, cx),
756 }
757 }
758
759 fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
760 if self.draft_active {
761 return self.send_new_chat(outgoing, window, cx);
762 }
763 let in_feed = self.in_feed();
764 if in_feed && outgoing.edit.is_none() {
765 outgoing.subject = self.take_subject(window, cx);
766 }
767 if in_feed {
768 self.close_new_post(cx);
769 }
770 match &outgoing.edit {
771 Some(edit) if edit.scheduled.is_some() => {
772 self.send_scheduled_edit(outgoing, window, cx)
773 }
774 Some(_) => self.send_edit(outgoing, window, cx),
775 None => self.send(outgoing, window, cx),
776 }
777 }
778
779 fn typing_root(&self) -> Option<String> {
780 match self.current.as_ref().map(|current| &current.mode) {
781 Some(ViewMode::Thread(root_id)) => Some(root_id.clone()),
782 _ => None,
783 }
784 }
785
786 fn send_typing(&self, active: bool, cx: &App) {
787 self.send_typing_in(self.typing_root(), active, cx);
788 }
789
790 fn send_typing_in(&self, thread_root_id: Option<String>, active: bool, cx: &App) {
791 let state = self.app.read(cx);
792 if state.mode.demo || state.mode.read_only || self.draft_active {
793 return;
794 }
795 let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id())
796 else {
797 return;
798 };
799 drop(runtime::spawn(async move {
800 let sent = engine
801 .send_typing(&conversation_id, thread_root_id.as_deref(), active)
802 .await;
803 if let Err(error) = sent
804 && cfg!(debug_assertions)
805 {
806 crate::diagnostics::record(format!("typing indicator not sent: {error}"));
807 }
808 }));
809 }
810
811 fn stop_typing(&mut self, cx: &mut Context<Self>) {
812 if self
813 .composer
814 .update(cx, |composer, _| composer.stop_typing())
815 {
816 self.send_typing(false, cx);
817 }
818 }
819
820 fn render_typing_line(&self, cx: &App) -> impl IntoElement {
821 let app = self.app.read(cx);
822 let faces = self
823 .current
824 .as_ref()
825 .filter(|_| !self.draft_active)
826 .map(|current| app.typing.faces(current.selection.conversation_id()))
827 .unwrap_or_default();
828 let tooltip_text = typing_tooltip(
829 &faces
830 .iter()
831 .map(|face| face.name.clone())
832 .collect::<Vec<_>>(),
833 );
834 let flat = matches!(
835 self.current.as_ref().map(|current| &current.mode),
836 Some(ViewMode::Flat)
837 );
838 let faces_element = match faces.as_slice() {
839 [face] if flat => person_avatar(
840 &app.directory,
841 face.user_id.as_deref(),
842 &face.name,
843 AVATAR_SIZE,
844 ),
845 _ => member_stack(&app.directory, &faces, faces.len(), true).into_any_element(),
846 };
847 h_flex()
848 .h(px(if flat {
849 AVATAR_SIZE + 4.
850 } else {
851 TYPING_LINE_HEIGHT
852 }))
853 .flex_none()
854 .px(px(20.))
855 .gap(px(if flat { AVATAR_GAP } else { 6. }))
856 .items_center()
857 .when(!faces.is_empty(), |line| {
858 line.child(
859 div()
860 .id("typing-faces")
861 .tooltip(move |window, cx| {
862 Tooltip::new(tooltip_text.clone()).build(window, cx)
863 })
864 .child(faces_element),
865 )
866 .child(typing_dots())
867 })
868 }
869
870 fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context<Self>) {
871 if self
872 .find_panel
873 .as_ref()
874 .is_some_and(|panel| panel.read(cx).selection() != &selection)
875 {
876 self.find_panel = None;
877 self.find_subscription = None;
878 }
879 self.stop_typing(cx);
880 self.stop_reply_typing(cx);
881 self.new_post_open = false;
882 self.feed_stash = None;
883 self.feed_at_top = true;
884 self.restore_subject(None, window, cx);
885 self.toolbar_hovered = None;
886 self.toolbar_pinned = None;
887 self.toolbar_suppressed = None;
888 self.agent_layouts.clear();
889 self.agent_runs.borrow_mut().clear();
890 self.reaction_proposals.borrow_mut().clear();
891 let title = selection_title(&self.app.read(cx).sidebar, &selection);
892 let mode = match selection {
893 Selection::Chat(_) => ViewMode::Flat,
894 Selection::Channel(_) => ViewMode::ThreadList,
895 };
896 let first_unread = self.first_unread_id(&selection, cx);
897 self.current = Some(Current {
898 loaded_limit: open_limit(&selection),
899 selection,
900 title,
901 mode,
902 loaded_count: 0,
903 has_older: false,
904 loading_older: false,
905 older_blocked: false,
906 fetched: false,
907 first_unread,
908 sync: SyncProgress::default(),
909 detached: None,
910 window_request: None,
911 });
912 self.refresh_agent_runs(cx);
913 self.refresh_reaction_pills(cx);
914 self.sync_generation += 1;
915 self.reset_channel_tabs(cx);
916 self.reset_recap(cx);
917 self.reload_pending(cx);
918 self.notice = None;
919 self.scheduled_failure = None;
920 self.app.update(cx, |state, cx| state.refresh_scheduled(cx));
921 self.rebuild(true, cx);
922 self.start_fetch(cx);
923 self.mark_read(ReadTrigger::Open, cx);
924 self.refresh_pin_previews(cx);
925 self.pinned_posts_expanded = false;
926 if let Some(conversation_id) = self.pin_conversation_id() {
927 self.app
928 .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx));
929 }
930 let target = self
931 .current
932 .as_ref()
933 .map(|current| {
934 (
935 current.selection.conversation_id().to_owned(),
936 composer_name(&self.app.read(cx).sidebar, &current.selection),
937 )
938 })
939 .unwrap_or_default();
940 self.composer.update(cx, |composer, cx| {
941 composer.set_conversation(&target.0, &target.1, window, cx);
942 });
943 self.sync_reply_composer(window, cx);
944 if !self.draft_active && !self.in_feed() {
945 self.composer
946 .update(cx, |composer, cx| composer.focus(window, cx));
947 }
948 self.hovered_message = None;
949 self.apply_pending_jump(cx);
950 }
951
952 fn enter_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
953 if !self.draft_active {
954 self.stop_typing(cx);
955 self.draft_active = true;
956 self.current = None;
957 self.clear_pending();
958 self.notice = None;
959 self.draft_created = None;
960 self.draft_error = None;
961 self.toolbar_hovered = None;
962 self.toolbar_pinned = None;
963 self.toolbar_suppressed = None;
964 self.hovered_message = None;
965 self.sync_generation += 1;
966 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
967 self.composer.update(cx, |composer, cx| {
968 composer.set_conversation("", "", window, cx)
969 });
970 self.on_draft_changed(window, cx);
971 self.rebuild(true, cx);
972 }
973 let people = self
974 .app
975 .update(cx, |state, _| std::mem::take(&mut state.new_chat_people));
976 if !people.is_empty() {
977 let chips = people
978 .into_iter()
979 .filter_map(|person| {
980 Some(Pick {
981 user_id: person.user_id?,
982 name: person.display_name,
983 mail: None,
984 })
985 })
986 .collect();
987 self.draft
988 .update(cx, |draft, cx| draft.set_chips(chips, cx));
989 }
990 self.draft
991 .update(cx, |draft, cx| draft.focus_query(window, cx));
992 cx.notify();
993 }
994
995 fn leave_draft(&mut self, window: &mut Window, cx: &mut Context<Self>) {
996 self.draft_active = false;
997 self.draft_created = None;
998 self.draft_error = None;
999 self.clear_pending();
1000 self.draft.update(cx, |draft, cx| draft.reset(window, cx));
1001 }
1002
1003 fn on_draft_event(
1004 &mut self,
1005 _: &Entity<NewChatDraft>,
1006 event: &NewChatEvent,
1007 window: &mut Window,
1008 cx: &mut Context<Self>,
1009 ) {
1010 match event {
1011 NewChatEvent::Changed => self.on_draft_changed(window, cx),
1012 NewChatEvent::FocusComposer => self
1013 .composer
1014 .update(cx, |composer, cx| composer.focus(window, cx)),
1015 NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)),
1016 }
1017 }
1018
1019 fn draft_target_chat(&self, cx: &App) -> Option<String> {
1020 let chips = self.draft.read(cx).chips();
1021 let [chip] = chips else {
1022 return None;
1023 };
1024 let state = self.app.read(cx);
1025 existing_one_on_one(
1026 &state.sidebar.chats,
1027 state.directory.me.as_ref(),
1028 &chip.user_id,
1029 )
1030 .map(|chat| chat.id.clone())
1031 }
1032
1033 fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1034 if !self.draft_active {
1035 return;
1036 }
1037 let target = self.draft_target_chat(cx);
1038 if target != self.conversation_id() {
1039 match target {
1040 Some(chat_id) => {
1041 self.composer.update(cx, |composer, _| {
1042 composer.carry_images_into(chat_id.clone())
1043 });
1044 self.open(Selection::Chat(chat_id), window, cx)
1045 }
1046 None => {
1047 self.composer.update(cx, |composer, cx| {
1048 composer.carry_images_into(String::new());
1049 composer.set_conversation("", "", window, cx);
1050 });
1051 self.current = None;
1052 self.sync_generation += 1;
1053 self.rebuild(true, cx);
1054 }
1055 }
1056 }
1057 let placeholder = {
1058 let draft = self.draft.read(cx);
1059 composer_placeholder(draft.chips(), &draft.group_name(cx))
1060 };
1061 self.composer.update(cx, |composer, cx| {
1062 composer.set_placeholder(&placeholder, window, cx)
1063 });
1064 cx.notify();
1065 }
1066
1067 fn remeasure_images(&mut self, keys: &[String], cx: &mut Context<Self>) {
1068 let indices: Vec<usize> = self
1069 .rows
1070 .borrow()
1071 .iter()
1072 .enumerate()
1073 .filter(|(_, row)| {
1074 row.messages().any(|message| {
1075 message.images.iter().any(|image| keys.contains(&image.url))
1076 || message
1077 .link_preview
1078 .as_ref()
1079 .and_then(LinkPreview::image)
1080 .is_some_and(|image| keys.contains(&image.url))
1081 })
1082 })
1083 .map(|(index, _)| index)
1084 .collect();
1085 self.scroller.update(cx, |scroller, cx| {
1086 for index in indices {
1087 scroller.remeasure_items(index..index + 1, cx);
1088 }
1089 });
1090 cx.notify();
1091 }
1092
1093 fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
1094 let is_current = self
1095 .current
1096 .as_ref()
1097 .is_some_and(|current| current.selection.conversation_id() == conversation_id);
1098 if !is_current {
1099 return;
1100 }
1101 self.rebuild(false, cx);
1102 let indices: Vec<usize> = self
1103 .rows
1104 .borrow()
1105 .iter()
1106 .enumerate()
1107 .filter(|(_, row)| {
1108 row.messages()
1109 .any(|message| !message.adaptive_cards.is_empty())
1110 })
1111 .map(|(index, _)| index)
1112 .collect();
1113 self.scroller.update(cx, |scroller, cx| {
1114 for index in indices {
1115 scroller.remeasure_items(index..index + 1, cx);
1116 }
1117 });
1118 cx.notify();
1119 }
1120
1121 fn apply_pending_jump(&mut self, cx: &mut Context<Self>) {
1122 let Some(conversation_id) = self
1123 .current
1124 .as_ref()
1125 .map(|current| current.selection.conversation_id().to_owned())
1126 else {
1127 return;
1128 };
1129 let jump = self
1130 .app
1131 .update(cx, |state, _| match state.pending_jump.take() {
1132 Some((target, message_id)) if target == conversation_id => Some(message_id),
1133 other => {
1134 state.pending_jump = other;
1135 None
1136 }
1137 });
1138 if let Some(message_id) = jump {
1139 self.jump_to_message(&conversation_id, &message_id, cx);
1140 }
1141 }
1142
1143 fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context<Self>) {
1144 let store = self.app.read(cx).store.clone();
1145 let record = store
1146 .messages_by_id(conversation_id, &[message_id.to_owned()])
1147 .ok()
1148 .and_then(|mut found| found.remove(message_id));
1149 if self.chat_id().as_deref() == Some(conversation_id) {
1150 let created_at = record.as_ref().map(|record| record.created_at);
1151 match self.jump_plan_for(conversation_id, created_at, cx) {
1152 JumpPlan::LoadWindow => {
1153 self.open_detached(conversation_id.to_owned(), message_id.to_owned(), cx);
1154 return;
1155 }
1156 plan => {
1157 if let Some(current) = self.current.as_mut() {
1158 current.window_request = None;
1159 if plan == JumpPlan::LeaveWindow {
1160 current.detached = None;
1161 }
1162 }
1163 }
1164 }
1165 }
1166 let Some(record) = record else {
1167 return;
1168 };
1169 let messages_from_target = store
1170 .messages(conversation_id, None, JUMP_SCAN_LIMIT)
1171 .ok()
1172 .and_then(|all| {
1173 all.iter()
1174 .position(|candidate| candidate.message_id == message_id)
1175 .map(|position| all.len() - position)
1176 })
1177 .unwrap_or_default();
1178 let row_key = record
1179 .reply_to_id
1180 .clone()
1181 .unwrap_or_else(|| message_id.to_owned());
1182 let Some(current) = self.current.as_mut() else {
1183 return;
1184 };
1185 current.loaded_limit = current
1186 .loaded_limit
1187 .max(messages_from_target + JUMP_CONTEXT_MESSAGES);
1188 current.first_unread = None;
1189 let in_channel = matches!(current.selection, Selection::Channel(_));
1190 if in_channel {
1191 self.pane = ChannelPane::Posts;
1192 match record.reply_to_id.clone() {
1193 Some(root_id) => {
1194 self.enter_thread_mode(root_id.clone(), cx);
1195 self.refresh_thread(root_id, cx);
1196 }
1197 None => {
1198 self.enter_feed_mode();
1199 }
1200 }
1201 }
1202 let in_thread = self
1203 .current
1204 .as_ref()
1205 .is_some_and(|current| matches!(current.mode, ViewMode::Thread(_)));
1206 let target_key = if in_thread {
1207 message_id.to_owned()
1208 } else {
1209 row_key
1210 };
1211 self.reload_pending(cx);
1212 self.rebuild(true, cx);
1213 self.reveal_row(target_key, cx);
1214 }
1215
1216 fn reveal_row(&mut self, target_key: String, cx: &mut Context<Self>) {
1217 let index = self
1218 .rows
1219 .borrow()
1220 .iter()
1221 .position(|row| row.key() == target_key);
1222 if let Some(index) = index {
1223 self.scroller
1224 .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx));
1225 self.highlight(target_key, cx);
1226 }
1227 }
1228
1229 fn highlight(&mut self, key: String, cx: &mut Context<Self>) {
1230 self.highlighted_message = Some(key.clone());
1231 cx.notify();
1232 cx.spawn(async move |this, cx| {
1233 cx.background_executor().timer(HIGHLIGHT_DURATION).await;
1234 this.update(cx, |this, cx| {
1235 if this.highlighted_message.as_deref() == Some(key.as_str()) {
1236 this.highlighted_message = None;
1237 cx.notify();
1238 }
1239 })
1240 .ok();
1241 })
1242 .detach();
1243 }
1244
1245 pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context<Self>) {
1246 self.composer
1247 .update(cx, |composer, cx| composer.set_text(text, window, cx));
1248 self.composer
1249 .update(cx, |composer, cx| composer.focus(window, cx));
1250 }
1251
1252 pub fn focus_composer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1253 self.composer
1254 .update(cx, |composer, cx| composer.focus(window, cx));
1255 }
1256
1257 pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1258 let key = self
1259 .rows
1260 .borrow()
1261 .iter()
1262 .rev()
1263 .flat_map(Row::messages)
1264 .find(|message| !message.own)
1265 .map(|message| message.key.clone());
1266 if let Some(key) = key {
1267 self.begin_reply(&key, window, cx);
1268 }
1269 }
1270
1271 pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1272 if let Some(message_id) = self.hovered_message.clone() {
1273 self.begin_reply(&message_id, window, cx);
1274 }
1275 }
1276
1277 fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> {
1278 let conversation_id = self.conversation_id()?;
1279 let record = self
1280 .app
1281 .read(cx)
1282 .store
1283 .messages_by_id(&conversation_id, &[message_id.to_owned()])
1284 .ok()
1285 .and_then(|mut found| found.remove(message_id))
1286 .filter(|record| !record.deleted)?;
1287 let preview = ReplyPreview {
1288 message_id: record.message_id.clone(),
1289 author: record
1290 .sender_name
1291 .clone()
1292 .unwrap_or_else(|| "Unknown".to_owned()),
1293 excerpt: reply_excerpt(&record),
1294 };
1295 Some((record, preview))
1296 }
1297
1298 fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
1299 let Some((record, preview)) = self.reply_target(message_id, cx) else {
1300 return;
1301 };
1302 if self.in_feed() {
1303 let root_id = record
1304 .reply_to_id
1305 .clone()
1306 .unwrap_or_else(|| record.message_id.clone());
1307 self.open_reply_editor(root_id, Some(preview), window, cx);
1308 return;
1309 }
1310 self.composer.update(cx, |composer, cx| {
1311 composer.set_reply(Some(preview), cx);
1312 composer.focus(window, cx);
1313 });
1314 }
1315
1316 fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option<String> {
1317 let Selection::Chat(chat_id) = selection else {
1318 return None;
1319 };
1320 let state = self.app.read(cx);
1321 if state.mode.demo {
1322 return crate::demo::first_unread(chat_id);
1323 }
1324 state.engine.as_ref()?.first_unread_message_id(chat_id)
1325 }
1326
1327 fn row_context(&self, cx: &App) -> RowContext {
1328 let now = Local::now();
1329 let app = self.app.read(cx);
1330 let names = local_names(app);
1331 let card_overrides = self
1332 .current
1333 .as_ref()
1334 .map(|current| app.cards.overrides_for(current.selection.conversation_id()))
1335 .unwrap_or_default();
1336 let translation = self
1337 .current
1338 .as_ref()
1339 .map(|current| {
1340 app.translation
1341 .context_for(current.selection.conversation_id())
1342 })
1343 .unwrap_or_default();
1344 RowContext {
1345 offset: now.offset().fix(),
1346 today: now.date_naive(),
1347 my_user_id: app.store.meta(META_USER_ID).ok().flatten(),
1348 names,
1349 pending_reactions: self.pending_reactions.clone(),
1350 card_overrides,
1351 translation,
1352 skin_tone: teams_core::skin_tone(&app.store),
1353 meeting: self.meeting_info(app),
1354 }
1355 }
1356
1357 fn unknown_reactor_ids(&self) -> Vec<String> {
1358 self.rows
1359 .borrow()
1360 .iter()
1361 .flat_map(Row::messages)
1362 .flat_map(|message| message.reactions.iter())
1363 .flat_map(|chip| chip.reactors.iter())
1364 .filter(|reactor| reactor.name == UNKNOWN_REACTOR)
1365 .filter_map(|reactor| reactor.user_id.clone())
1366 .collect()
1367 }
1368
1369 fn refresh_reactor_names(&mut self, cx: &mut Context<Self>) {
1370 if self.current.is_none() {
1371 return;
1372 }
1373 let unknown = self.unknown_reactor_ids();
1374 if unknown.is_empty() {
1375 return;
1376 }
1377 let names = resolve_names(self.app.read(cx), &unknown);
1378 if !names.is_empty() {
1379 self.rebuild(false, cx);
1380 }
1381 }
1382
1383 fn drop_stale_reaction_details(&mut self) {
1384 let Some(details) = self.reaction_details.as_ref() else {
1385 return;
1386 };
1387 let present = self
1388 .rows
1389 .borrow()
1390 .iter()
1391 .flat_map(Row::messages)
1392 .any(|message| {
1393 message.key == details.message_key
1394 && message
1395 .reactions
1396 .iter()
1397 .any(|chip| chip.glyph() == details.anchor_glyph)
1398 });
1399 if !present {
1400 self.reaction_details = None;
1401 }
1402 }
1403
1404 fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context<Self>) {
1405 let multiple_kinds = self
1406 .rows
1407 .borrow()
1408 .iter()
1409 .flat_map(Row::messages)
1410 .any(|message| message.key == message_key && message.reactions.len() > 1);
1411 self.reaction_details = Some(ReactionDetails {
1412 message_key: message_key.to_owned(),
1413 anchor_glyph: glyph.to_owned(),
1414 tab: multiple_kinds.then(|| glyph.to_owned()),
1415 });
1416 cx.notify();
1417 }
1418
1419 fn select_reaction_tab(&mut self, tab: Option<String>, cx: &mut Context<Self>) {
1420 if let Some(details) = self.reaction_details.as_mut() {
1421 details.tab = tab;
1422 cx.notify();
1423 }
1424 }
1425
1426 fn close_reaction_details(&mut self, cx: &mut Context<Self>) {
1427 if self.reaction_details.take().is_some() {
1428 cx.notify();
1429 }
1430 }
1431
1432 fn reaction_controls(&self, key: &str, view: WeakEntity<Self>) -> ReactionControls {
1433 let open = {
1434 let (view, key) = (view.clone(), key.to_owned());
1435 Rc::new(move |glyph: &str, cx: &mut App| {
1436 view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx))
1437 .ok();
1438 })
1439 };
1440 let select_tab = {
1441 let view = view.clone();
1442 Rc::new(move |tab: Option<String>, cx: &mut App| {
1443 view.update(cx, |this, cx| this.select_reaction_tab(tab, cx))
1444 .ok();
1445 })
1446 };
1447 let close = Rc::new(move |cx: &mut App| {
1448 view.update(cx, |this, cx| this.close_reaction_details(cx))
1449 .ok();
1450 });
1451 let popover = self
1452 .reaction_details
1453 .as_ref()
1454 .filter(|details| details.message_key == key)
1455 .map(|details| ReactionPopover {
1456 anchor_glyph: details.anchor_glyph.clone(),
1457 tab: details.tab.clone(),
1458 });
1459 ReactionControls {
1460 open,
1461 select_tab,
1462 close,
1463 popover,
1464 }
1465 }
1466
1467 fn start_info(&self, cx: &App) -> Option<StartInfo> {
1468 let current = self.current.as_ref()?;
1469 let app = self.app.read(cx);
1470 let user_id = match &current.selection {
1471 Selection::Chat(chat_id) => app
1472 .sidebar
1473 .chats
1474 .iter()
1475 .find(|chat| &chat.id == chat_id)
1476 .filter(|chat| is_one_on_one(chat))
1477 .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next())
1478 .and_then(|(user_id, _)| user_id),
1479 Selection::Channel(_) => None,
1480 };
1481 Some(StartInfo {
1482 title: current.title.clone(),
1483 user_id,
1484 })
1485 }
1486
1487 fn watch_feed_scroll(&mut self, cx: &mut Context<Self>) {
1488 let scroller_id = self.scroller.entity_id();
1489 if self
1490 .scroller_watch
1491 .as_ref()
1492 .is_some_and(|(watched, _)| *watched == scroller_id)
1493 {
1494 return;
1495 }
1496 let subscription = cx.observe(&self.scroller, |this, _, cx| {
1497 if this.in_feed() {
1498 cx.notify();
1499 }
1500 });
1501 self.scroller_watch = Some((scroller_id, subscription));
1502 }
1503
1504 fn rebuild(&mut self, reset: bool, cx: &mut Context<Self>) {
1505 let Some(current) = self.current.as_ref() else {
1506 let mut rows: Vec<Row> = self
1507 .pending
1508 .iter()
1509 .cloned()
1510 .map(|row| Row::Message(Box::new(row)))
1511 .collect();
1512 assign_series(&mut rows);
1513 self.apply_rows(rows, true, cx);
1514 return;
1515 };
1516 let conversation_id = current.selection.conversation_id().to_owned();
1517 let limit = if reset {
1518 current.loaded_limit
1519 } else {
1520 current
1521 .loaded_limit
1522 .max(current.loaded_count + GROWTH_HEADROOM)
1523 };
1524 let store = self.app.read(cx).store.clone();
1525 let thread_root = match &current.mode {
1526 ViewMode::Thread(root_id) => Some(root_id.clone()),
1527 ViewMode::Flat | ViewMode::ThreadList => None,
1528 };
1529 let sync_state = store.sync_state(&conversation_id).ok().flatten();
1530 let window = current.detached.as_ref().map(|detached| {
1531 (
1532 detached.oldest,
1533 detached.newest,
1534 detached.older_cursor.is_some(),
1535 detached.newer_cursor.is_some(),
1536 )
1537 });
1538 let records: Vec<MessageRecord> = match (&thread_root, window) {
1539 (Some(root_id), _) => store
1540 .thread_messages(&conversation_id, root_id)
1541 .unwrap_or_default(),
1542 (None, Some((oldest, newest, _, _))) => store
1543 .messages_between(&conversation_id, oldest, newest)
1544 .unwrap_or_default(),
1545 (None, None) if matches!(current.selection, Selection::Chat(_)) => without_islands(
1546 store
1547 .messages(&conversation_id, None, limit)
1548 .unwrap_or_default(),
1549 sync_state.as_ref().and_then(|state| state.oldest_loaded),
1550 ),
1551 (None, None) => store
1552 .messages(&conversation_id, None, limit)
1553 .unwrap_or_default(),
1554 };
1555 let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);
1556 let mut context = self.row_context(cx);
1557 let unnamed_ids: Vec<String> = records
1558 .iter()
1559 .flat_map(teams_core::reactions)
1560 .filter(|reaction| reaction.user_name.is_none())
1561 .filter_map(|reaction| reaction.user_id)
1562 .chain(forward_sender_ids(&records))
1563 .filter(|user_id| !context.names.contains_key(user_id))
1564 .collect();
1565 for (user_id, name) in resolve_names(self.app.read(cx), &unnamed_ids) {
1566 context.names.entry(user_id).or_insert(name);
1567 }
1568 for record in &records {
1569 if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) {
1570 context
1571 .names
1572 .entry(user_id.clone())
1573 .or_insert_with(|| name.clone());
1574 }
1575 }
1576 let can_load_older = self.app.read(cx).engine.is_some();
1577 let start = self.start_info(cx);
1578 let current = self.current.as_mut().expect("checked above");
1579 let first_unread = current.first_unread.clone();
1580 current.loaded_limit = limit;
1581 if thread_root.is_none() {
1582 current.loaded_count = records.len();
1583 }
1584 let has_older = sync_has_more && !current.older_blocked && can_load_older;
1585 let placeholders = current.sync.messages
1586 && records.is_empty()
1587 && !matches!(current.mode, ViewMode::Thread(_));
1588 let in_feed = current.mode == ViewMode::ThreadList;
1589 let mut rows = match &current.mode {
1590 _ if placeholders => {
1591 current.has_older = false;
1592 placeholder_rows()
1593 }
1594 ViewMode::Flat => match window {
1595 Some((_, _, has_older_window, has_newer_window)) => {
1596 current.has_older = has_older_window;
1597 let mut rows = flat_rows(&records, &context, has_older_window);
1598 if has_newer_window {
1599 rows.push(Row::LoadNewer);
1600 }
1601 rows
1602 }
1603 None => {
1604 current.has_older = has_older;
1605 let mut rows = flat_rows(&records, &context, has_older);
1606 if !has_older && let Some(start) = start {
1607 rows.insert(0, Row::Start(start));
1608 }
1609 rows
1610 }
1611 },
1612 ViewMode::ThreadList => {
1613 current.has_older = has_older;
1614 thread_list_rows(&records, &context, has_older)
1615 }
1616 ViewMode::Thread(root_id) => {
1617 current.has_older = false;
1618 thread_rows(&records, root_id, &context)
1619 }
1620 };
1621 let local: Vec<MessageRow> = if window.is_some() {
1622 Vec::new()
1623 } else {
1624 self.pending
1625 .iter()
1626 .cloned()
1627 .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx))
1628 .collect()
1629 };
1630 if in_feed {
1631 place_local_rows(&mut rows, local);
1632 } else {
1633 rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row))));
1634 }
1635 let mut receipts = self.receipts(&records, cx);
1636 if self.track_receipt_fades(&mut receipts) {
1637 self.schedule_fade_end(cx);
1638 }
1639 for row in rows.iter_mut() {
1640 if let Row::Message(message) = row
1641 && message.own
1642 {
1643 message.receipt = receipts.get(&message.key).copied().unwrap_or_default();
1644 }
1645 }
1646 if let Some(unread_id) = &first_unread {
1647 for row in rows.iter_mut() {
1648 if let Row::Message(message) = row
1649 && &message.key == unread_id
1650 {
1651 message.new_marker = true;
1652 }
1653 }
1654 }
1655 assign_series(&mut rows);
1656 self.apply_rows(rows, reset, cx);
1657 if self.is_detached() {
1658 self.scroller
1659 .update(cx, |scroller, _| scroller.stop_following());
1660 }
1661 }
1662
1663 fn apply_rows(&mut self, new_rows: Vec<Row>, reset: bool, cx: &mut Context<Self>) {
1664 let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows);
1665 self.drop_stale_reaction_details();
1666 let new_len = self.rows.borrow().len();
1667 let in_feed = self.in_feed();
1668 if reset {
1669 let marker_index = self
1670 .rows
1671 .borrow()
1672 .iter()
1673 .position(|row| matches!(row, Row::Message(message) if message.new_marker));
1674 self.feed_at_top = true;
1675 self.scroller.update(cx, |scroller, cx| {
1676 scroller.reset(new_len, cx);
1677 if in_feed {
1678 scroller.scroll_to_item(0, cx);
1679 return;
1680 }
1681 match marker_index {
1682 Some(index) if !scroller.scroll_to_item(index, cx) => {
1683 scroller.scroll_to_end(cx)
1684 }
1685 Some(_) => {}
1686 None => scroller.scroll_to_end(cx),
1687 }
1688 });
1689 cx.notify();
1690 return;
1691 }
1692 let (splice, changed) = {
1693 let new_rows = self.rows.borrow();
1694 let old_keys: Vec<String> = old_rows.iter().map(|row| row.key().to_owned()).collect();
1695 let new_keys: Vec<String> = new_rows.iter().map(|row| row.key().to_owned()).collect();
1696 (
1697 diff_keys(&old_keys, &new_keys),
1698 changed_indices(&old_rows, &new_rows),
1699 )
1700 };
1701 let top_changed = splice
1702 .as_ref()
1703 .is_some_and(|splice| splice.range.start == 0);
1704 let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed));
1705 self.scroller.update(cx, |scroller, cx| {
1706 if let Some(splice) = splice
1707 && !scroller.splice(splice.range, splice.count, cx)
1708 {
1709 scroller.reset(new_len, cx);
1710 }
1711 if keep_top {
1712 scroller.scroll_to_item(0, cx);
1713 }
1714 for index in changed {
1715 scroller.remeasure_items(index..index + 1, cx);
1716 }
1717 });
1718 cx.notify();
1719 }
1720
1721 fn start_fetch(&mut self, cx: &mut Context<Self>) {
1722 let state = self.app.read(cx);
1723 let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync);
1724 if engine.is_none() && demo_sync.is_none() {
1725 return;
1726 }
1727 let Some(current) = self.current.as_mut() else {
1728 return;
1729 };
1730 if current.fetched {
1731 return;
1732 }
1733 current.fetched = true;
1734 let is_chat = matches!(current.selection, Selection::Chat(_));
1735 let newest_cached = self
1736 .rows
1737 .borrow()
1738 .iter()
1739 .flat_map(Row::messages)
1740 .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX))
1741 .map(|message| message.created_at)
1742 .max();
1743 let current = self.current.as_mut().expect("checked above");
1744 if current.sync.failed {
1745 self.notice = None;
1746 }
1747 current.sync = SyncProgress {
1748 messages: true,
1749 receipts: is_chat,
1750 empty_cache: newest_cached.is_none(),
1751 newest_cached,
1752 ..SyncProgress::default()
1753 };
1754 self.sync_generation += 1;
1755 let generation = self.sync_generation;
1756 let conversation_id = current.selection.conversation_id().to_owned();
1757 match (engine, demo_sync) {
1758 (Some(engine), _) => {
1759 let receiver =
1760 runtime::spawn(async move { engine.fetch_newer(&conversation_id).await });
1761 cx.spawn(async move |this, cx| {
1762 let result = receiver.await;
1763 this.update(cx, |this, cx| this.finish_fetch(generation, result, cx))
1764 .ok();
1765 })
1766 .detach();
1767 }
1768 (None, Some(delay)) => self.simulate_sync(generation, delay, cx),
1769 (None, None) => {}
1770 }
1771 self.schedule_progress(generation, cx);
1772 self.rebuild(false, cx);
1773 self.mark_read(ReadTrigger::Incoming, cx);
1774 self.refresh_receipts(generation, cx);
1775 }
1776
1777 fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context<Self>) {
1778 cx.spawn(async move |this, cx| {
1779 cx.background_executor().timer(delay).await;
1780 this.update(cx, |this, cx| {
1781 if let Some(sync) = this.sync_of(generation) {
1782 sync.receipts = false;
1783 }
1784 this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx)
1785 })
1786 .ok();
1787 })
1788 .detach();
1789 }
1790
1791 fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> {
1792 if generation != self.sync_generation {
1793 return None;
1794 }
1795 self.current.as_mut().map(|current| &mut current.sync)
1796 }
1797
1798 fn schedule_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1799 cx.spawn(async move |this, cx| {
1800 let stages = [
1801 (PROGRESS_DELAY, Duration::ZERO),
1802 (SLOW_AFTER, PROGRESS_DELAY),
1803 ];
1804 for (stage, (at, previous)) in stages.into_iter().enumerate() {
1805 cx.background_executor().timer(at - previous).await;
1806 let running = this
1807 .update(cx, |this, cx| this.advance_progress(generation, stage, cx))
1808 .unwrap_or(false);
1809 if !running {
1810 return;
1811 }
1812 }
1813 })
1814 .detach();
1815 }
1816
1817 fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context<Self>) -> bool {
1818 let Some(sync) = self.sync_of(generation) else {
1819 return false;
1820 };
1821 if !sync.running() {
1822 return false;
1823 }
1824 match stage {
1825 0 => sync.shown_at = Some(Instant::now()),
1826 _ => sync.slow = true,
1827 }
1828 cx.notify();
1829 true
1830 }
1831
1832 fn finish_fetch(
1833 &mut self,
1834 generation: u64,
1835 result: Result<
1836 teams_core::Result<teams_core::Delta>,
1837 tokio::sync::oneshot::error::RecvError,
1838 >,
1839 cx: &mut Context<Self>,
1840 ) {
1841 let Some(sync) = self.sync_of(generation) else {
1842 return;
1843 };
1844 sync.messages = false;
1845 let newest_cached = sync.newest_cached;
1846 match result {
1847 Ok(Ok(_)) => self.mark_fetched_new(newest_cached, cx),
1848 Ok(Err(error)) => self.fail_sync(generation, short_error(&error)),
1849 Err(error) => self.fail_sync(generation, short_error(&error)),
1850 }
1851 self.rebuild(false, cx);
1852 self.settle_progress(generation, cx);
1853 }
1854
1855 fn fail_sync(&mut self, generation: u64, error: String) {
1856 if let Some(sync) = self.sync_of(generation) {
1857 sync.failed = true;
1858 sync.receipts = false;
1859 }
1860 self.notice = Some(format!("Could not refresh: {error}"));
1861 }
1862
1863 fn mark_fetched_new(&mut self, newest_cached: Option<DateTime<Utc>>, cx: &mut Context<Self>) {
1864 let Some(newest_cached) = newest_cached else {
1865 return;
1866 };
1867 let Some(my_user_id) = self.row_context(cx).my_user_id else {
1868 return;
1869 };
1870 let store = self.app.read(cx).store.clone();
1871 let Some(current) = self.current.as_mut() else {
1872 return;
1873 };
1874 if current.first_unread.is_some() || current.mode != ViewMode::Flat {
1875 return;
1876 }
1877 let limit = current
1878 .loaded_limit
1879 .max(current.loaded_count + GROWTH_HEADROOM);
1880 current.first_unread = store
1881 .messages(current.selection.conversation_id(), None, limit)
1882 .unwrap_or_default()
1883 .into_iter()
1884 .find(|record| {
1885 record.created_at > newest_cached && record.sender_id.as_ref() != Some(&my_user_id)
1886 })
1887 .map(|record| record.message_id);
1888 }
1889
1890 fn settle_progress(&mut self, generation: u64, cx: &mut Context<Self>) {
1891 let Some(sync) = self.sync_of(generation) else {
1892 return;
1893 };
1894 if sync.running() {
1895 return;
1896 }
1897 let remaining = sync
1898 .shown_at
1899 .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed()))
1900 .unwrap_or_default();
1901 if remaining.is_zero() {
1902 sync.shown_at = None;
1903 sync.slow = false;
1904 cx.notify();
1905 return;
1906 }
1907 cx.spawn(async move |this, cx| {
1908 cx.background_executor().timer(remaining).await;
1909 this.update(cx, |this, cx| {
1910 if let Some(sync) = this.sync_of(generation) {
1911 sync.shown_at = None;
1912 sync.slow = false;
1913 cx.notify();
1914 }
1915 })
1916 .ok();
1917 })
1918 .detach();
1919 }
1920
1921 fn retry_fetch(&mut self, cx: &mut Context<Self>) {
1922 if let Some(current) = self.current.as_mut() {
1923 current.fetched = false;
1924 }
1925 self.start_fetch(cx);
1926 }
1927
1928 fn receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1929 let settings = self.app.read(cx).account_chat_settings();
1930 let mut receipts = self.raw_receipts(records, cx);
1931 for receipt in receipts.values_mut() {
1932 *receipt = shown_receipt(&settings, *receipt);
1933 }
1934 receipts
1935 }
1936
1937 fn raw_receipts(&self, records: &[MessageRecord], cx: &App) -> HashMap<String, Receipt> {
1938 let state = self.app.read(cx);
1939 if state.mode.demo {
1940 let read_ids = crate::demo::read_message_ids(records);
1941 return records
1942 .iter()
1943 .map(|record| {
1944 let receipt = if read_ids.contains(&record.message_id) {
1945 Receipt::Read
1946 } else {
1947 Receipt::Sent
1948 };
1949 (record.message_id.clone(), receipt)
1950 })
1951 .collect();
1952 }
1953 let Some(engine) = state.engine.as_ref() else {
1954 return HashMap::new();
1955 };
1956 records
1957 .iter()
1958 .map(|record| {
1959 let receipt = match engine.receipt_state_for(record) {
1960 teams_core::ReceiptState::Read { .. } => Receipt::Read,
1961 teams_core::ReceiptState::Sent => Receipt::Sent,
1962 teams_core::ReceiptState::Unknown => Receipt::Hidden,
1963 };
1964 (record.message_id.clone(), receipt)
1965 })
1966 .collect()
1967 }
1968
1969 fn track_receipt_fades(&mut self, receipts: &mut HashMap<String, Receipt>) -> bool {
1970 let Some(current) = self.current.as_ref() else {
1971 return false;
1972 };
1973 let settled = !current.sync.receipts;
1974 let conversation_id = current.selection.conversation_id().to_owned();
1975 self.receipt_fade
1976 .apply(&conversation_id, settled, receipts, Instant::now())
1977 }
1978
1979 fn schedule_fade_end(&mut self, cx: &mut Context<Self>) {
1980 cx.spawn(async move |this, cx| {
1981 cx.background_executor()
1982 .timer(receipt_fade::RECEIPT_FADE)
1983 .await;
1984 this.update(cx, |this, cx| this.rebuild(false, cx)).ok();
1985 })
1986 .detach();
1987 }
1988
1989 fn refresh_receipts(&mut self, generation: u64, cx: &mut Context<Self>) {
1990 let state = self.app.read(cx);
1991 let (Some(engine), Some(Selection::Chat(chat_id))) = (
1992 state.engine.clone(),
1993 self.current.as_ref().map(|c| c.selection.clone()),
1994 ) else {
1995 return;
1996 };
1997 let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await });
1998 cx.spawn(async move |this, cx| {
1999 receiver.await.ok();
2000 this.update(cx, |this, cx| {
2001 let Some(sync) = this.sync_of(generation) else {
2002 return;
2003 };
2004 sync.receipts = false;
2005 this.rebuild(false, cx);
2006 this.settle_progress(generation, cx);
2007 })
2008 .ok();
2009 })
2010 .detach();
2011 }
2012
2013 fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context<Self>) {
2014 if self.draft_active {
2015 return;
2016 }
2017 let state = self.app.read(cx);
2018 if state.viewing_call() && !self.pinned {
2019 return;
2020 }
2021 let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else {
2022 return;
2023 };
2024 if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only {
2025 return;
2026 }
2027 let unread = match &selection {
2028 Selection::Chat(chat_id) => {
2029 state
2030 .sidebar
2031 .chats
2032 .iter()
2033 .any(|chat| &chat.id == chat_id && chat.unread)
2034 && !state.keeps_unread(chat_id)
2035 }
2036 Selection::Channel(channel_id) => channel_unread(&state.sidebar, channel_id),
2037 };
2038 let Some(plan) = plan_read(self.window_active, unread, trigger) else {
2039 return;
2040 };
2041 self.app.update(cx, |state, cx| match &selection {
2042 Selection::Chat(chat_id) => {
2043 state.ack_urgent_messages(chat_id, cx);
2044 state.mark_chat_read(chat_id, cx)
2045 }
2046 Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx),
2047 });
2048 if plan.clear_divider
2049 && let Some(current) = self.current.as_mut()
2050 && current.first_unread.take().is_some()
2051 {
2052 self.rebuild(false, cx);
2053 }
2054 }
2055
2056 fn request_older(&mut self, cx: &mut Context<Self>) {
2057 if self.is_detached() {
2058 return self.request_window_page(WindowDirection::Backward, cx);
2059 }
2060 let Some(engine) = self.app.read(cx).engine.clone() else {
2061 return;
2062 };
2063 let Some(current) = self.current.as_mut() else {
2064 return;
2065 };
2066 if current.loading_older || current.older_blocked || !current.has_older {
2067 return;
2068 }
2069 current.loading_older = true;
2070 let conversation_id = current.selection.conversation_id().to_owned();
2071 let task_id = conversation_id.clone();
2072 let receiver = runtime::spawn(async move { engine.load_older(&task_id).await });
2073 cx.spawn(async move |this, cx| {
2074 let result = receiver.await;
2075 this.update(cx, |this, cx| {
2076 this.finish_older(&conversation_id, result, cx)
2077 })
2078 .ok();
2079 })
2080 .detach();
2081 }
2082
2083 fn finish_older(
2084 &mut self,
2085 conversation_id: &str,
2086 result: Result<
2087 teams_core::Result<Vec<MessageRecord>>,
2088 tokio::sync::oneshot::error::RecvError,
2089 >,
2090 cx: &mut Context<Self>,
2091 ) {
2092 let Some(current) = self.current.as_mut() else {
2093 return;
2094 };
2095 if current.selection.conversation_id() != conversation_id {
2096 return;
2097 }
2098 current.loading_older = false;
2099 match result {
2100 Ok(Ok(records)) if !records.is_empty() => {
2101 current.loaded_limit = current.loaded_count + records.len();
2102 }
2103 Ok(Ok(_)) => current.older_blocked = true,
2104 Ok(Err(error)) => {
2105 current.older_blocked = true;
2106 self.notice = Some(format!(
2107 "Could not load older messages: {}",
2108 short_error(&error)
2109 ));
2110 }
2111 Err(_) => current.older_blocked = true,
2112 }
2113 self.rebuild(false, cx);
2114 }
2115
2116 fn clear_pending(&mut self) {
2117 self.pending.clear();
2118 self.pending_outgoing.clear();
2119 }
2120
2121 fn outbox_route(&self, reply_root: Option<String>) -> (OutboxTarget, Option<String>) {
2122 if let Some(root_id) = reply_root {
2123 return (OutboxTarget::Thread, Some(root_id));
2124 }
2125 match self.current.as_ref().map(|current| &current.mode) {
2126 Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())),
2127 Some(ViewMode::ThreadList) => (OutboxTarget::Post, None),
2128 _ => (OutboxTarget::Flat, None),
2129 }
2130 }
2131
2132 fn reload_pending(&mut self, cx: &App) {
2133 self.clear_pending();
2134 let state = self.app.read(cx);
2135 if state.mode.demo || state.mode.read_only {
2136 return;
2137 }
2138 let Some(current) = self.current.as_ref() else {
2139 return;
2140 };
2141 let conversation_id = current.selection.conversation_id().to_owned();
2142 let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else {
2143 return;
2144 };
2145 let my_user_id = state.store.meta(META_USER_ID).ok().flatten();
2146 let mut pending = Vec::new();
2147 for record in records {
2148 if !shown_in_view(&current.mode, &record) {
2149 continue;
2150 }
2151 let Some(outgoing) = outgoing_of(&record) else {
2152 continue;
2153 };
2154 let delivery = match record.state {
2155 OutboxState::Sending => Delivery::Sending,
2156 OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()),
2157 };
2158 let mut row = pending_row(
2159 record.id.clone(),
2160 conversation_id.clone(),
2161 my_user_id.clone(),
2162 record.created_at,
2163 &outgoing,
2164 delivery,
2165 );
2166 row.reply_root = record.thread_root_id.clone();
2167 pending.push((row, record.id, outgoing));
2168 }
2169 for (row, id, outgoing) in pending {
2170 self.pending.push(row);
2171 self.pending_outgoing.insert(id, outgoing);
2172 }
2173 }
2174
2175 fn discard_outbox_row(&self, id: &str, cx: &mut Context<Self>) {
2176 self.app.read(cx).store.delete_outbox(id).ok();
2177 self.app
2178 .update(cx, |state, cx| state.refresh_local_previews(cx));
2179 }
2180
2181 fn delete_pending(&mut self, key: &str, cx: &mut Context<Self>) {
2182 self.pending.retain(|row| row.key != key);
2183 self.pending_outgoing.remove(key);
2184 self.discard_outbox_row(key, cx);
2185 self.rebuild(false, cx);
2186 }
2187
2188 fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2189 self.leave_detached(cx);
2190 self.send_as(new_outbox_id(), outgoing, None, window, cx);
2191 }
2192
2193 fn send_in_thread(
2194 &mut self,
2195 root_id: String,
2196 outgoing: Outgoing,
2197 window: &mut Window,
2198 cx: &mut Context<Self>,
2199 ) {
2200 self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx);
2201 }
2202
2203 fn send_as(
2204 &mut self,
2205 id: String,
2206 outgoing: Outgoing,
2207 reply_root: Option<String>,
2208 window: &mut Window,
2209 cx: &mut Context<Self>,
2210 ) {
2211 let state = self.app.read(cx);
2212 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2213 let Some(current) = self.current.as_ref() else {
2214 return;
2215 };
2216 if mode.read_only || mode.demo {
2217 self.restore_unsent(
2218 "Read-only mode: nothing was sent",
2219 &outgoing,
2220 reply_root.as_deref(),
2221 window,
2222 cx,
2223 );
2224 return;
2225 }
2226 let Some(engine) = engine else {
2227 self.discard_outbox_row(&id, cx);
2228 self.restore_unsent(
2229 "Not connected yet: nothing was sent",
2230 &outgoing,
2231 reply_root.as_deref(),
2232 window,
2233 cx,
2234 );
2235 return;
2236 };
2237 let conversation_id = current.selection.conversation_id().to_owned();
2238 let (target, thread_root_id) = self.outbox_route(reply_root);
2239 let created_at = Utc::now();
2240 self.push_pending(
2241 id.clone(),
2242 created_at,
2243 &outgoing,
2244 thread_root_id.clone(),
2245 cx,
2246 );
2247 if let Some(record) = outbox_record(
2248 &id,
2249 &conversation_id,
2250 target,
2251 thread_root_id.as_deref(),
2252 &outgoing,
2253 created_at,
2254 ) {
2255 store.put_outbox(&record).ok();
2256 }
2257 self.notice = None;
2258 self.rebuild(false, cx);
2259 if self.in_feed() {
2260 self.scroller
2261 .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx));
2262 } else {
2263 self.scroller
2264 .update(cx, |scroller, cx| scroller.scroll_to_end(cx));
2265 }
2266
2267 let receiver = runtime::spawn(async move {
2268 deliver(
2269 &engine,
2270 &conversation_id,
2271 target,
2272 thread_root_id.as_deref(),
2273 &outgoing,
2274 )
2275 .await
2276 });
2277 cx.spawn_in(window, async move |this, cx| {
2278 let result = receiver.await;
2279 this.update(cx, |this, cx| this.finish_send(&id, result, cx))
2280 .ok();
2281 })
2282 .detach();
2283 }
2284
2285 fn restore_unsent(
2286 &mut self,
2287 message: &str,
2288 outgoing: &Outgoing,
2289 reply_root: Option<&str>,
2290 window: &mut Window,
2291 cx: &mut Context<Self>,
2292 ) {
2293 self.notice = Some(message.to_owned());
2294 if let (Some(root_id), true) = (reply_root, self.in_feed()) {
2295 self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx);
2296 if let Some(composer) = self.reply_composer.clone() {
2297 composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2298 }
2299 } else {
2300 self.show_main_composer(cx);
2301 self.restore_subject(outgoing.subject.as_deref(), window, cx);
2302 self.composer
2303 .update(cx, |composer, cx| composer.restore(outgoing, window, cx));
2304 }
2305 cx.notify();
2306 }
2307
2308 fn next_pending_key(&mut self) -> String {
2309 self.pending_counter += 1;
2310 format!("{PENDING_KEY_PREFIX}{}", self.pending_counter)
2311 }
2312
2313 fn push_pending(
2314 &mut self,
2315 key: String,
2316 created_at: DateTime<Utc>,
2317 outgoing: &Outgoing,
2318 reply_root: Option<String>,
2319 cx: &App,
2320 ) {
2321 let my_user_id = self.row_context(cx).my_user_id;
2322 let conversation_id = self
2323 .current
2324 .as_ref()
2325 .map(|current| current.selection.conversation_id().to_owned())
2326 .unwrap_or_default();
2327 let mut row = pending_row(
2328 key.clone(),
2329 conversation_id,
2330 my_user_id,
2331 created_at,
2332 outgoing,
2333 Delivery::Sending,
2334 );
2335 row.reply_root = reply_root;
2336 self.pending.push(row);
2337 self.pending_outgoing.insert(key, outgoing.clone());
2338 }
2339
2340 fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2341 let (recipients, topic) = {
2342 let draft = self.draft.read(cx);
2343 let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty());
2344 (draft.chips().to_vec(), topic)
2345 };
2346 if recipients.is_empty() {
2347 self.restore_unsent("Add at least one person first", &outgoing, None, window, cx);
2348 self.draft
2349 .update(cx, |draft, cx| draft.focus_query(window, cx));
2350 return;
2351 }
2352 if self
2353 .pending
2354 .iter()
2355 .any(|row| matches!(row.delivery, Delivery::Sending))
2356 {
2357 self.restore_unsent("Still creating the chat", &outgoing, None, window, cx);
2358 return;
2359 }
2360 let state = self.app.read(cx);
2361 let (mode, engine) = (state.mode, state.engine.clone());
2362 if mode.read_only {
2363 self.restore_unsent(
2364 "Read-only mode: nothing was sent",
2365 &outgoing,
2366 None,
2367 window,
2368 cx,
2369 );
2370 return;
2371 }
2372 if mode.demo && outgoing.has_attachments() {
2373 self.restore_unsent(
2374 "Read-only mode: nothing was sent",
2375 &outgoing,
2376 None,
2377 window,
2378 cx,
2379 );
2380 return;
2381 }
2382 if mode.demo {
2383 self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx);
2384 return;
2385 }
2386 let Some(engine) = engine else {
2387 self.restore_unsent(
2388 "Not connected yet: nothing was sent",
2389 &outgoing,
2390 None,
2391 window,
2392 cx,
2393 );
2394 return;
2395 };
2396 let user_ids: Vec<String> = recipients.into_iter().map(|pick| pick.user_id).collect();
2397 let known_chat = self
2398 .draft_created
2399 .as_ref()
2400 .filter(|(created_for, _)| *created_for == user_ids)
2401 .map(|(_, chat_id)| chat_id.clone())
2402 .or_else(|| self.draft_target_chat(cx));
2403 self.pending.clear();
2404 self.pending_outgoing.clear();
2405 self.draft_error = None;
2406 self.notice = None;
2407 let key = self.next_pending_key();
2408 self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx);
2409 self.rebuild(true, cx);
2410 let recipients_for_finish = user_ids.clone();
2411 let receiver = runtime::spawn(async move {
2412 let chat_id = match known_chat {
2413 Some(chat_id) => chat_id,
2414 None => {
2415 let created = match user_ids.as_slice() {
2416 [user_id] => engine.create_one_on_one(user_id).await,
2417 _ => engine.create_group(&user_ids, topic.as_deref()).await,
2418 };
2419 match created {
2420 Ok(chat_id) => chat_id,
2421 Err(error) => return (None, Some(short_error(&error))),
2422 }
2423 }
2424 };
2425 let sent = engine
2426 .send_message_with_extras(
2427 &chat_id,
2428 &outgoing.html(),
2429 None,
2430 &outgoing.mentions,
2431 &outgoing.extras(),
2432 )
2433 .await;
2434 if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
2435 let _ = engine
2436 .attach_link_preview(&chat_id, &record.message_id, preview)
2437 .await;
2438 }
2439 (Some(chat_id), sent.err().map(|error| short_error(&error)))
2440 });
2441 cx.spawn_in(window, async move |this, cx| {
2442 let result = receiver.await;
2443 this.update_in(cx, |this, _, cx| {
2444 this.finish_new_chat(&key, recipients_for_finish, result, cx)
2445 })
2446 .ok();
2447 })
2448 .detach();
2449 }
2450
2451 fn finish_new_chat(
2452 &mut self,
2453 key: &str,
2454 user_ids: Vec<String>,
2455 result: Result<(Option<String>, Option<String>), tokio::sync::oneshot::error::RecvError>,
2456 cx: &mut Context<Self>,
2457 ) {
2458 if !self.draft_active || !self.pending.iter().any(|row| row.key == key) {
2459 return;
2460 }
2461 let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned())));
2462 self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id));
2463 match (chat_id, error) {
2464 (Some(chat_id), None) => {
2465 self.app.update(cx, |state, cx| {
2466 state.reload_sidebar(cx);
2467 state.select(Selection::Chat(chat_id), cx);
2468 });
2469 }
2470 (created, error) => {
2471 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
2472 row.delivery = Delivery::Failed(error.unwrap_or_default());
2473 }
2474 self.draft_error = Some(
2475 if created.is_some() {
2476 "Couldn't send the message."
2477 } else {
2478 "Couldn't create the chat."
2479 }
2480 .to_owned(),
2481 );
2482 self.rebuild(false, cx);
2483 }
2484 }
2485 }
2486
2487 fn send_demo_new_chat(
2488 &mut self,
2489 outgoing: &Outgoing,
2490 recipients: &[super::new_chat::Pick],
2491 topic: Option<&str>,
2492 cx: &mut Context<Self>,
2493 ) {
2494 let (store, chats) = {
2495 let state = self.app.read(cx);
2496 (state.store.clone(), state.sidebar.chats.clone())
2497 };
2498 let people: Vec<(String, String)> = recipients
2499 .iter()
2500 .map(|pick| (pick.user_id.clone(), pick.name.clone()))
2501 .collect();
2502 let (chat, message) = match self.draft_target_chat(cx) {
2503 Some(chat_id) => {
2504 let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else {
2505 return;
2506 };
2507 crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now())
2508 }
2509 None => crate::demo::new_chat(
2510 &chats,
2511 &people,
2512 topic,
2513 &outgoing.text(),
2514 &outgoing.html(),
2515 Utc::now(),
2516 ),
2517 };
2518 let _ = store.upsert_chats(std::slice::from_ref(&chat));
2519 let _ = store.upsert_messages(std::slice::from_ref(&message));
2520 self.app.update(cx, |state, cx| {
2521 state.reload_sidebar(cx);
2522 state.select(Selection::Chat(chat.id.clone()), cx);
2523 });
2524 }
2525
2526 fn conversation_id(&self) -> Option<String> {
2527 self.current
2528 .as_ref()
2529 .map(|current| current.selection.conversation_id().to_owned())
2530 }
2531
2532 fn own_record(&self, message_id: &str, cx: &App) -> Option<MessageRecord> {
2533 let conversation_id = self.conversation_id()?;
2534 let my_user_id = self.row_context(cx).my_user_id?;
2535 self.app
2536 .read(cx)
2537 .store
2538 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2539 .ok()?
2540 .remove(message_id)
2541 .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id))
2542 }
2543
2544 fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context<Self>) {
2545 let target = match slot {
2546 HoverSlot::Row => &mut self.hovered_message,
2547 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2548 };
2549 if hovered {
2550 *target = Some(key.to_owned());
2551 } else if target.as_deref() == Some(key) {
2552 *target = None;
2553 }
2554 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
2555 && self.hovered_message.as_deref() != Some(suppressed)
2556 && self.toolbar_hovered.as_deref() != Some(suppressed)
2557 {
2558 self.toolbar_suppressed = None;
2559 }
2560 cx.notify();
2561 }
2562
2563 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2564 if self.toolbar_hovered.as_deref() == Some(key) {
2565 self.toolbar_hovered = None;
2566 }
2567 self.toolbar_suppressed = Some(key.to_owned());
2568 cx.notify();
2569 }
2570
2571 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
2572 if open {
2573 self.toolbar_pinned = Some(key.to_owned());
2574 } else if self.toolbar_pinned.as_deref() == Some(key) {
2575 self.toolbar_pinned = None;
2576 }
2577 cx.notify();
2578 }
2579
2580 fn toolbar_visible(&self, key: &str) -> bool {
2581 self.toolbar_suppressed.as_deref() != Some(key)
2582 && self
2583 .toolbar_pinned
2584 .as_deref()
2585 .or(self.toolbar_hovered.as_deref())
2586 .or(self.hovered_message.as_deref())
2587 == Some(key)
2588 }
2589
2590 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
2591 self.change_reaction(message_id, glyph, false, None, cx);
2592 }
2593
2594 fn change_reaction(
2595 &mut self,
2596 message_id: &str,
2597 glyph: &str,
2598 only_add: bool,
2599 accepted_proposal: Option<String>,
2600 cx: &mut Context<Self>,
2601 ) -> ReactionAttempt {
2602 let Some(conversation_id) = self.conversation_id() else {
2603 return ReactionAttempt::Blocked;
2604 };
2605 let state = self.app.read(cx);
2606 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2607 let engine = engine.filter(|_| !mode.read_only);
2608 if !mode.demo && engine.is_none() {
2609 self.show_notice("Read-only mode: reaction not sent", cx);
2610 return ReactionAttempt::Blocked;
2611 }
2612 let my_user_id = self.row_context(cx).my_user_id;
2613 let Some(mut record) = store
2614 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2615 .ok()
2616 .and_then(|mut found| found.remove(message_id))
2617 else {
2618 return ReactionAttempt::MissingMessage;
2619 };
2620 let wanted = reaction_glyph(glyph);
2621 let mut visible = teams_core::reactions(&record);
2622 apply_pending_reactions(
2623 &mut visible,
2624 self.pending_reactions.get(message_id),
2625 my_user_id.as_deref(),
2626 Utc::now(),
2627 );
2628 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
2629 if only_add && !added {
2630 return ReactionAttempt::AlreadyThere;
2631 }
2632 let skin_tone = teams_core::skin_tone(&store);
2633 let wanted = if added {
2634 wanted
2635 } else {
2636 let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);
2637 if emoticons::without_tone(&own) == own {
2638 emoticons::with_tone(&own, skin_tone)
2639 } else {
2640 own
2641 }
2642 };
2643 let glyph = wanted.as_str();
2644 let Some(engine) = engine.filter(|_| !mode.demo) else {
2645 let mut reactions = teams_core::reactions(&record);
2646 set_own_reaction(
2647 &mut reactions,
2648 glyph,
2649 my_user_id.as_deref(),
2650 added,
2651 Utc::now(),
2652 );
2653 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2654 let _ = store.upsert_messages(std::slice::from_ref(&record));
2655 if added {
2656 self.record_reaction_use(glyph, cx);
2657 }
2658 self.rebuild(false, cx);
2659 return ReactionAttempt::Acted;
2660 };
2661 let entries = self
2662 .pending_reactions
2663 .entry(message_id.to_owned())
2664 .or_default();
2665 entries.retain(|(pending, _)| {
2666 emoticons::without_tone(pending) != emoticons::without_tone(&wanted)
2667 });
2668 entries.push((wanted.clone(), added));
2669 self.rebuild(false, cx);
2670 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
2671 let reaction_type = api_reaction(&wanted);
2672 let receiver = runtime::spawn({
2673 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
2674 async move {
2675 if added {
2676 engine
2677 .set_reaction(&conversation_id, &message_id, &reaction_type)
2678 .await
2679 } else {
2680 engine
2681 .unset_reaction(&conversation_id, &message_id, &reaction_type)
2682 .await
2683 }
2684 }
2685 });
2686 cx.spawn(async move |this, cx| {
2687 let outcome = match receiver.await {
2688 Ok(Ok(())) => Ok(()),
2689 Ok(Err(error)) => Err(short_error(&error)),
2690 Err(_) => Err("cancelled".to_owned()),
2691 };
2692 this.update(cx, |this, cx| {
2693 this.finish_reaction(
2694 &conversation_id,
2695 &message_id,
2696 &glyph,
2697 added,
2698 accepted_proposal.as_deref(),
2699 outcome,
2700 cx,
2701 )
2702 })
2703 .ok();
2704 })
2705 .detach();
2706 ReactionAttempt::Started
2707 }
2708
2709 fn finish_reaction(
2710 &mut self,
2711 conversation_id: &str,
2712 message_id: &str,
2713 glyph: &str,
2714 added: bool,
2715 accepted_proposal: Option<&str>,
2716 outcome: Result<(), String>,
2717 cx: &mut Context<Self>,
2718 ) {
2719 let wanted = reaction_glyph(glyph);
2720 let store = self.app.read(cx).store.clone();
2721 if let Some(proposal_id) = accepted_proposal.filter(|_| outcome.is_ok()) {
2722 crate::agent_api::resolve_reaction_proposal(
2723 conversation_id,
2724 message_id,
2725 proposal_id,
2726 mcp::ReactionOutcome::Accepted,
2727 cx,
2728 );
2729 }
2730 if outcome.is_ok() {
2731 let my_user_id = self.row_context(cx).my_user_id;
2732 if let Some(mut record) = store
2733 .messages_by_id(conversation_id, &[message_id.to_owned()])
2734 .ok()
2735 .and_then(|mut found| found.remove(message_id))
2736 {
2737 let mut reactions = teams_core::reactions(&record);
2738 set_own_reaction(
2739 &mut reactions,
2740 glyph,
2741 my_user_id.as_deref(),
2742 added,
2743 Utc::now(),
2744 );
2745 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2746 let _ = store.upsert_messages(std::slice::from_ref(&record));
2747 }
2748 if added {
2749 self.record_reaction_use(glyph, cx);
2750 }
2751 }
2752 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
2753 entries.retain(|entry| *entry != (wanted.clone(), added));
2754 if entries.is_empty() {
2755 self.pending_reactions.remove(message_id);
2756 }
2757 }
2758 self.rebuild(false, cx);
2759 if let Err(error) = outcome {
2760 self.show_notice(&format!("Reaction failed: {error}"), cx);
2761 }
2762 }
2763
2764 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2765 if chatsvc::custom_emoji(glyph).is_some() {
2766 return;
2767 }
2768 let store = self.app.read(cx).store.clone();
2769 self.recent.update(cx, |recent, cx| {
2770 recent.reload(&store);
2771 recent.record_use(&emoticons::without_tone(glyph));
2772 recent.save(&store);
2773 cx.notify();
2774 });
2775 }
2776
2777 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
2778 let Some(record) = self.own_record(message_id, cx) else {
2779 return;
2780 };
2781 let edit = EditPreview {
2782 message_id: record.message_id.clone(),
2783 excerpt: reply_excerpt(&record),
2784 scheduled: None,
2785 };
2786 let in_chat = matches!(
2787 self.current.as_ref().map(|current| &current.selection),
2788 Some(Selection::Chat(_))
2789 );
2790 let mentions = if in_chat {
2791 teams_core::user_mention_inputs(&record)
2792 } else {
2793 Vec::new()
2794 };
2795 let draft = Outgoing {
2796 draft: message_draft(&record),
2797 subject: None,
2798 mentions,
2799 reply: None,
2800 edit: Some(edit),
2801 images: Vec::new(),
2802 files: Vec::new(),
2803 link_preview: None,
2804 importance: Default::default(),
2805 };
2806 self.show_main_composer(cx);
2807 self.composer
2808 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2809 }
2810
2811 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2812 if self.draft_active {
2813 return;
2814 }
2815 let key = self
2816 .rows
2817 .borrow()
2818 .iter()
2819 .flat_map(Row::messages)
2820 .filter(|message| {
2821 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2822 })
2823 .max_by_key(|message| message.created_at)
2824 .map(|message| message.key.clone());
2825 if let Some(key) = key {
2826 self.begin_edit(&key, window, cx);
2827 }
2828 }
2829
2830 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2831 let Some(edit) = outgoing.edit.clone() else {
2832 return;
2833 };
2834 let Some(conversation_id) = self.conversation_id() else {
2835 return;
2836 };
2837 let state = self.app.read(cx);
2838 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2839 if mode.demo {
2840 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
2841 record.body_html = outgoing.html();
2842 record.edited_at = Some(Utc::now());
2843 let _ = store.upsert_messages(std::slice::from_ref(&record));
2844 self.rebuild(false, cx);
2845 }
2846 return;
2847 }
2848 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2849 self.notice = Some("Read-only mode: edit not saved".to_owned());
2850 self.show_main_composer(cx);
2851 self.composer
2852 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2853 cx.notify();
2854 return;
2855 };
2856 let sent = outgoing.clone();
2857 let receiver = runtime::spawn(async move {
2858 engine
2859 .edit_message_html(
2860 &conversation_id,
2861 &edit.message_id,
2862 &sent.html(),
2863 &sent.mentions,
2864 )
2865 .await
2866 });
2867 cx.spawn_in(window, async move |this, cx| {
2868 let failed = !matches!(receiver.await, Ok(Ok(())));
2869 this.update_in(cx, |this, window, cx| {
2870 if failed {
2871 this.show_main_composer(cx);
2872 if this.composer.read(cx).is_empty(cx) {
2873 this.notice =
2874 Some("Edit failed: your text is back in the composer".to_owned());
2875 this.composer
2876 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2877 } else {
2878 this.notice = Some("Edit failed".to_owned());
2879 }
2880 cx.notify();
2881 }
2882 })
2883 .ok();
2884 })
2885 .detach();
2886 }
2887
2888 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2889 let Some(conversation_id) = self.conversation_id() else {
2890 return;
2891 };
2892 let record = self
2893 .app
2894 .read(cx)
2895 .store
2896 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2897 .ok()
2898 .and_then(|mut found| found.remove(message_id));
2899 if let Some(record) = record {
2900 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
2901 }
2902 }
2903
2904 fn refresh_card(
2905 &mut self,
2906 key: &str,
2907 card_index: usize,
2908 action: ExecuteAction,
2909 cx: &mut Context<Self>,
2910 ) {
2911 let Some(conversation_id) = self.conversation_id() else {
2912 return;
2913 };
2914 let scope = CardScope::message(&conversation_id, key, card_index);
2915 self.app.update(cx, |state, cx| {
2916 state.refresh_card_manually(scope, action, cx)
2917 });
2918 }
2919
2920 pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) {
2921 let Some(conversation_id) = self.conversation_id() else {
2922 return;
2923 };
2924 self.app.update(cx, |state, cx| {
2925 state.translate_message(&conversation_id, key, cx)
2926 });
2927 }
2928
2929 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2930 self.app.update(cx, |state, cx| {
2931 state.raise_notice(message.to_owned(), None, cx)
2932 });
2933 }
2934
2935 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2936 let (Some(conversation_id), Some(runs)) =
2937 (self.conversation_id(), crate::agents::runs_handle(cx))
2938 else {
2939 return (Vec::new(), None);
2940 };
2941 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
2942 return (Vec::new(), None);
2943 }
2944 let settings = runs.read(cx).settings();
2945 let entries: Vec<DelegateEntry> = settings
2946 .actions
2947 .iter()
2948 .map(|action| {
2949 let request = StartRequest {
2950 action_id: action.id.clone(),
2951 conversation_id: conversation_id.clone(),
2952 message_id: key.to_owned(),
2953 };
2954 let agent_name = settings
2955 .agents
2956 .iter()
2957 .find(|agent| agent.id == action.agent_id)
2958 .map(|agent| agent.name.clone())
2959 .unwrap_or_default();
2960 DelegateEntry {
2961 label: action.label.clone(),
2962 agent_name,
2963 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
2964 }
2965 })
2966 .collect();
2967 let manage_agents = (!entries.is_empty()).then(|| {
2968 Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
2969 });
2970 (entries, manage_agents)
2971 }
2972
2973 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
2974 let Some(conversation_id) = self.conversation_id() else {
2975 return (false, HashSet::new());
2976 };
2977 let Some(runs) = crate::agents::runs_handle(cx) else {
2978 return (false, HashSet::new());
2979 };
2980 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
2981 for run in runs.read(cx).for_conversation(&conversation_id) {
2982 snapshot.insert(run.message_id.clone(), run.clone());
2983 }
2984 let layouts: HashMap<String, (usize, bool)> = snapshot
2985 .iter()
2986 .map(|(key, run)| (key.clone(), run.layout_key()))
2987 .collect();
2988 let layout_changed: HashSet<String> = layouts
2989 .iter()
2990 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
2991 .map(|(key, _)| key.clone())
2992 .chain(
2993 self.agent_layouts
2994 .keys()
2995 .filter(|key| !layouts.contains_key(*key))
2996 .cloned(),
2997 )
2998 .collect();
2999 self.agent_layouts = layouts;
3000 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
3001 *self.agent_runs.borrow_mut() = snapshot;
3002 (snapshot_changed, layout_changed)
3003 }
3004
3005 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
3006 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
3007 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
3008 self.remeasure_rows_of(&changed, cx);
3009 if snapshot_changed || any_running {
3010 cx.notify();
3011 }
3012 }
3013
3014 fn remeasure_rows_of(&mut self, keys: &HashSet<String>, cx: &mut Context<Self>) {
3015 if keys.is_empty() {
3016 return;
3017 }
3018 let indices: Vec<usize> = self
3019 .rows
3020 .borrow()
3021 .iter()
3022 .enumerate()
3023 .filter(|(_, row)| row.messages().any(|message| keys.contains(&message.key)))
3024 .map(|(index, _)| index)
3025 .collect();
3026 self.scroller.update(cx, |scroller, cx| {
3027 for index in indices {
3028 scroller.remeasure_items(index..index + 1, cx);
3029 }
3030 });
3031 }
3032
3033 fn message_menu(
3034 &self,
3035 message: &MessageRow,
3036 mine: HashSet<String>,
3037 refresh: Option<(usize, ExecuteAction)>,
3038 view: WeakEntity<Self>,
3039 cx: &App,
3040 ) -> MessageMenu {
3041 let (key, own) = (message.key.as_str(), message.own);
3042 let translate_label = match message.translation {
3043 Some(TranslationLine::Translated {
3044 showing_original: false,
3045 ..
3046 }) => "See original",
3047 Some(TranslationLine::Translated { .. }) => "See translation",
3048 _ => "Translate",
3049 };
3050 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
3051 let (view, key) = (view.clone(), key.to_owned());
3052 Rc::new(move |window, cx| {
3053 view.update(cx, |this, cx| run(this, &key, window, cx)).ok();
3054 })
3055 };
3056 let react: PickHandler = {
3057 let (view, key) = (view.clone(), key.to_owned());
3058 Rc::new(move |glyph, _, cx| {
3059 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
3060 .ok();
3061 })
3062 };
3063 let hover = {
3064 let (view, key) = (view.clone(), key.to_owned());
3065 Rc::new(move |hovered: bool, cx: &mut App| {
3066 view.update(cx, |this, cx| {
3067 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
3068 })
3069 .ok();
3070 })
3071 };
3072 let pin = {
3073 let (view, key) = (view.clone(), key.to_owned());
3074 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
3075 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
3076 .ok();
3077 })
3078 };
3079 let refresh_card = refresh.map(|(card_index, refresh_action)| {
3080 let (view, key) = (view.clone(), key.to_owned());
3081 Rc::new(move |_: &mut Window, cx: &mut App| {
3082 view.update(cx, |this, cx| {
3083 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
3084 })
3085 .ok();
3086 }) as Action
3087 });
3088 let chat_id = self.chat_id();
3089 let state = self.app.read(cx);
3090 let saved = self
3091 .conversation_id()
3092 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3093 let quick = state.quick_reactions();
3094 let in_chat = chat_id.is_some();
3095 let pin_conversation_id = self.pin_conversation_id();
3096 let pinned = pin_conversation_id
3097 .as_deref()
3098 .is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3099 let pinnable = in_chat
3100 || pin_conversation_id.as_deref().is_some_and(|channel_id| {
3101 state
3102 .message_record(channel_id, key)
3103 .is_some_and(|record| record.reply_to_id.is_none())
3104 });
3105 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3106 MessageMenu {
3107 key: key.to_owned(),
3108 react,
3109 reply: Some(action(|this, key, window, cx| {
3110 this.begin_reply(key, window, cx)
3111 })),
3112 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3113 forward_multiple: in_chat
3114 .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))),
3115 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3116 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3117 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
3118 translate_label,
3119 share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))),
3120 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3121 saved,
3122 toggle_pinned: pinnable
3123 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3124 pinned,
3125 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3126 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3127 mark_unread: (in_chat && !own)
3128 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
3129 refresh_card,
3130 delegate,
3131 manage_agents,
3132 pin,
3133 hover,
3134 picker: self.picker.clone(),
3135 quick,
3136 mine,
3137 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3138 }
3139 }
3140
3141 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
3142 let Some(outgoing) = self.pending_outgoing.remove(key) else {
3143 return;
3144 };
3145 let reply_root = self
3146 .pending
3147 .iter()
3148 .find(|row| row.key == key)
3149 .and_then(|row| row.reply_root.clone());
3150 self.pending.retain(|row| row.key != key);
3151 if self.draft_active {
3152 self.send_new_chat(outgoing, window, cx);
3153 } else {
3154 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
3155 }
3156 }
3157
3158 fn finish_send(
3159 &mut self,
3160 key: &str,
3161 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
3162 cx: &mut Context<Self>,
3163 ) {
3164 let failure = match result {
3165 Ok(Ok(())) => None,
3166 Ok(Err(error)) => Some(short_error(&error)),
3167 Err(error) => Some(short_error(&error)),
3168 };
3169 let store = self.app.read(cx).store.clone();
3170 match failure {
3171 None => {
3172 store.delete_outbox(key).ok();
3173 self.pending.retain(|row| row.key != key);
3174 self.pending_outgoing.remove(key);
3175 }
3176 Some(error) => {
3177 store.mark_outbox_failed(key, &error).ok();
3178 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
3179 row.delivery = Delivery::Failed(error.clone());
3180 self.notice = Some(format!("Not sent: {error}"));
3181 }
3182 }
3183 }
3184 self.app
3185 .update(cx, |state, cx| state.refresh_local_previews(cx));
3186 self.rebuild(false, cx);
3187 }
3188
3189 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3190 let target = match self.current.as_ref().map(|current| &current.selection) {
3191 Some(Selection::Chat(_)) => DropTarget::Chat,
3192 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
3193 Some(Selection::Channel(_)) => DropTarget::Channel,
3194 None => DropTarget::NewChat,
3195 };
3196 let title = self
3197 .current
3198 .as_ref()
3199 .map(|current| current.title.as_str())
3200 .unwrap_or_default();
3201 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
3202 let composer = self.composer.clone();
3203 div()
3204 .id("drop-overlay")
3205 .absolute()
3206 .top_0()
3207 .left_0()
3208 .size_full()
3209 .opacity(0.)
3210 .bg(theme::drop_background())
3211 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
3212 if composer.read(cx).is_editing() {
3213 style
3214 } else {
3215 style.opacity(1.)
3216 }
3217 })
3218 .on_drag_move(
3219 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
3220 let count = event.drag(cx).paths().len();
3221 if this.drag_file_count != count {
3222 this.drag_file_count = count;
3223 cx.notify();
3224 }
3225 }),
3226 )
3227 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
3228 let paths = dropped.paths().to_vec();
3229 if this.shared_active() {
3230 this.upload_paths(paths, cx);
3231 return;
3232 }
3233 this.composer
3234 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
3235 }))
3236 .child(
3237 div()
3238 .absolute()
3239 .inset(px(12.))
3240 .rounded(px(12.))
3241 .border_2()
3242 .border_color(theme::accent())
3243 .flex()
3244 .items_center()
3245 .justify_center()
3246 .child(
3247 v_flex()
3248 .items_center()
3249 .gap(px(6.))
3250 .px(px(24.))
3251 .py(px(16.))
3252 .rounded(px(12.))
3253 .bg(black().opacity(0.55))
3254 .child(symbol("upload", 28., theme::accent_text()))
3255 .child(
3256 div()
3257 .text_size(px(15.))
3258 .font_weight(FontWeight::SEMIBOLD)
3259 .text_color(theme::text_strong())
3260 .child(heading),
3261 )
3262 .child(
3263 div()
3264 .text_size(px(12.))
3265 .text_color(theme::text_muted())
3266 .child(detail),
3267 ),
3268 ),
3269 )
3270 }
3271
3272 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
3273 let message = self.draft_error.clone()?;
3274 let failed_key = self
3275 .pending
3276 .iter()
3277 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
3278 .map(|row| row.key.clone())?;
3279 Some(
3280 h_flex()
3281 .w_full()
3282 .flex_none()
3283 .px(px(20.))
3284 .py(px(4.))
3285 .gap(px(8.))
3286 .items_center()
3287 .text_size(px(12.))
3288 .text_color(theme::red_soft())
3289 .child(message)
3290 .child(
3291 Button::new("retry-new-chat")
3292 .ghost()
3293 .compact()
3294 .label("Retry")
3295 .on_click(cx.listener(move |this, _, window, cx| {
3296 this.retry(&failed_key, window, cx)
3297 })),
3298 ),
3299 )
3300 }
3301
3302 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3303 if self.pinned || self.draft_active {
3304 return;
3305 }
3306 let Some(selection) = self
3307 .current
3308 .as_ref()
3309 .map(|current| current.selection.clone())
3310 else {
3311 return;
3312 };
3313 self.channel_details_open = false;
3314 if let Some(panel) = &self.find_panel {
3315 panel.update(cx, |panel, cx| panel.focus(window, cx));
3316 return;
3317 }
3318 let app = self.app.clone();
3319 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3320 let subscription = cx.subscribe_in(
3321 &panel,
3322 window,
3323 move |this, _, event: &FindPanelEvent, window, cx| match event {
3324 FindPanelEvent::Close => this.close_find(window, cx),
3325 FindPanelEvent::Jump(message_id) => {
3326 let (selection, message_id) = (selection.clone(), message_id.clone());
3327 this.app.update(cx, |state, cx| {
3328 state.jump_to_message(selection, message_id, cx)
3329 });
3330 }
3331 },
3332 );
3333 panel.update(cx, |panel, cx| panel.focus(window, cx));
3334 self.find_panel = Some(panel);
3335 self.find_subscription = Some(subscription);
3336 cx.notify();
3337 }
3338
3339 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3340 self.find_panel = None;
3341 self.find_subscription = None;
3342 self.composer
3343 .update(cx, |composer, cx| composer.focus(window, cx));
3344 cx.notify();
3345 }
3346
3347 fn header_width(&self, window: &Window) -> f32 {
3348 match self.header_width.get() {
3349 width if width > 0. => width,
3350 _ => {
3351 f32::from(window.viewport_size().width)
3352 - RAIL_WIDTH
3353 - SIDEBAR_WIDTH
3354 - 2. * ISLAND_GAP
3355 }
3356 }
3357 }
3358
3359 fn tabs_below_title(&self, window: &Window) -> bool {
3360 self.header_width(window) < TABS_INLINE_MIN_WIDTH
3361 }
3362
3363 fn render_header(
3364 &self,
3365 current: &Current,
3366 tabs: Option<AnyElement>,
3367 cx: &mut Context<Self>,
3368 ) -> impl IntoElement {
3369 let app = self.app.read(cx);
3370 let directory = &app.directory;
3371 let me = directory.me.as_ref();
3372 let mut lead: Option<AnyElement> = None;
3373 let mut subline = String::new();
3374 let mut stack: Option<AnyElement> = None;
3375 let mut rename: Option<AnyElement> = None;
3376 match &current.selection {
3377 Selection::Chat(chat_id) => {
3378 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3379 let faces = others(chat, me);
3380 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3381 let first = faces.first().cloned().map(face);
3382 if let Some(bot) = one_on_one_bot(chat, me) {
3383 lead = Some(bot_tile(directory, &face(bot), 36.));
3384 } else if is_one_on_one(chat) || faces.len() < 2 {
3385 let name = first
3386 .as_ref()
3387 .map_or(current.title.as_str(), |face| face.name.as_str());
3388 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
3389 let avatar = person_avatar(directory, user_id, name, 36.);
3390 let presence = user_id.map(|id| directory.presence_of(id));
3391 let avatar = match presence {
3392 Some(kind) => with_presence(avatar, kind, 36., theme::surface())
3393 .into_any_element(),
3394 None => avatar,
3395 };
3396 lead = Some(
3397 opens_profile(div().id("header-avatar").flex_none(), user_id)
3398 .child(avatar)
3399 .into_any_element(),
3400 );
3401 subline = match (user_id, presence) {
3402 (Some(id), Some(presence)) => {
3403 directory.status_label(id, presence).to_owned()
3404 }
3405 _ => String::new(),
3406 };
3407 if is_one_on_one(chat) {
3408 stack = Some(add_people_button(&self.app, chat_id));
3409 }
3410 } else {
3411 if chat.kind == GROUP_KIND
3412 && me.is_some_and(|me| {
3413 chat.members
3414 .iter()
3415 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3416 })
3417 {
3418 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3419 }
3420 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3421 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3422 subline = format!("{} participants", chat.members.len());
3423 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
3424 stack = Some(members_popover(
3425 &self.app,
3426 chat_id,
3427 member_stack(directory, &shown, shown.len(), false)
3428 .debug_selector(|| MEMBERS_BUTTON.into()),
3429 ));
3430 }
3431 }
3432 }
3433 Selection::Channel(channel_id) => {
3434 let team = app.sidebar.teams.iter().find(|entry| {
3435 entry
3436 .channels
3437 .iter()
3438 .any(|channel| &channel.id == channel_id)
3439 });
3440 let (name, key) = team
3441 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
3442 (entry.team.name.as_str(), entry.team.id.as_str())
3443 });
3444 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
3445 }
3446 }
3447 let mut header = h_flex()
3448 .w_full()
3449 .h(px(HEADER_HEIGHT))
3450 .flex_none()
3451 .px(px(HEADER_PADDING))
3452 .gap(px(HEADER_GAP))
3453 .items_center();
3454 if matches!(current.mode, ViewMode::Thread(_)) {
3455 header = header.child(
3456 h_flex()
3457 .id("back-to-channel")
3458 .flex_none()
3459 .gap(px(2.))
3460 .pl(px(4.))
3461 .pr(px(8.))
3462 .py(px(4.))
3463 .items_center()
3464 .rounded(px(6.))
3465 .cursor_pointer()
3466 .text_size(px(13.))
3467 .font_weight(FontWeight::SEMIBOLD)
3468 .text_color(theme::accent_text())
3469 .hover(|button| button.bg(theme::row_hover()))
3470 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
3471 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
3472 .child("Back to channel"),
3473 );
3474 }
3475 let channel_note = match current.mode {
3476 ViewMode::Flat => None,
3477 ViewMode::ThreadList => Some("Posts"),
3478 ViewMode::Thread(_) => Some("Conversation"),
3479 };
3480 if let Some(note) = channel_note {
3481 subline = note.to_owned();
3482 }
3483 let call_controls = if self.pinned {
3484 Vec::new()
3485 } else {
3486 header_call_controls(&self.app, app, &current.selection)
3487 };
3488 let sync = &current.sync;
3489 let loading_window = current.window_request.is_some();
3490 if sync.failed {
3491 subline = "Not up to date".to_owned();
3492 } else if loading_window {
3493 subline = "Loading message ...".to_owned();
3494 } else if sync.shown_at.is_some() {
3495 subline = if sync.slow {
3496 "Taking longer than usual ..."
3497 } else if sync.empty_cache {
3498 "Loading messages ..."
3499 } else {
3500 "Updating ..."
3501 }
3502 .to_owned();
3503 }
3504 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3505 header
3506 .relative()
3507 .child(record_width(&self.header_width))
3508 .when(sync.shown_at.is_some() || loading_window, |header| {
3509 header.child(progress_bar())
3510 })
3511 .children(lead)
3512 .child(
3513 v_flex()
3514 .map(|column| match inline_tabs {
3515 Some(_) => column.flex_shrink(1.).max_w(px(HEADER_TITLE_MAX_WIDTH)),
3516 None => column.flex_1(),
3517 })
3518 .min_w_0()
3519 .overflow_hidden()
3520 .gap(px(1.))
3521 .child(
3522 h_flex()
3523 .min_w_0()
3524 .gap(px(2.))
3525 .items_center()
3526 .child(
3527 div()
3528 .truncate()
3529 .text_size(px(15.))
3530 .font_weight(FontWeight::SEMIBOLD)
3531 .text_color(theme::text())
3532 .child(current.title.clone()),
3533 )
3534 .children(rename),
3535 )
3536 .when(!subline.is_empty(), |column| {
3537 column.child(
3538 div()
3539 .text_size(px(12.))
3540 .text_color(theme::text_muted())
3541 .child(subline),
3542 )
3543 }),
3544 )
3545 .children(inline_tabs)
3546 .children(stack)
3547 .children(call_controls)
3548 .children(self.channel_details_button(cx))
3549 }
3550}
3551
3552const GROUP_KIND: &str = "group";
3553
3554impl Render for ConversationView {
3555 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3556 let background = theme::surface();
3557 let mut root = v_flex()
3558 .when(!self.pinned, |root| {
3559 root.debug_selector(|| "shell/islands/main".into())
3560 })
3561 .flex_1()
3562 .w_full()
3563 .min_w_0()
3564 .h_full()
3565 .rounded(px(10.))
3566 .bg(background)
3567 .track_focus(&self.focus_handle);
3568 let drafting = self.draft_active;
3569 if self.current.is_none() && !drafting {
3570 return root
3571 .items_center()
3572 .justify_center()
3573 .text_color(theme::text_muted())
3574 .child("Select a chat or channel")
3575 .into_any_element();
3576 }
3577 let in_feed = self.in_feed();
3578 let detached = self.is_detached();
3579 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3580 if in_feed && rows_seen != usize::MAX {
3581 self.feed_at_top = rows_seen == 0;
3582 }
3583 let forward_selection = self.active_forward_selection(cx);
3584 let rows = self.rows.clone();
3585 let rows_seen = self.feed_rows_seen.clone();
3586 let env = RenderEnv {
3587 view: cx.weak_entity(),
3588 app: self.app.clone(),
3589 highlighted: self.highlighted_message.clone(),
3590 drafting,
3591 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3592 timeline: self.timeline_bounds.clone(),
3593 agent_runs: self.agent_runs.clone(),
3594 reaction_proposals: self.reaction_proposals.clone(),
3595 forward_selection: forward_selection.clone(),
3596 };
3597 let pin_banner = self
3598 .render_pin_banner(cx)
3599 .filter(|_| !drafting && !self.shared_active() && !self.recap_active());
3600 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
3601 let scroller = MessageScroller::new(
3602 "messages",
3603 self.scroller.clone(),
3604 move |index, window, cx| {
3605 rows_seen.set(rows_seen.get().min(index));
3606 let rows = rows.borrow();
3607 match rows.get(index) {
3608 Some(Row::Message(message)) => {
3609 let actions = env.message_actions(message, window, cx);
3610 let state = env.app.read(cx);
3611 render_message_row(message, index, actions, &state.directory, cx)
3612 }
3613 Some(Row::Post(post)) => {
3614 let actions = env.post_actions(post, window, cx);
3615 let state = env.app.read(cx);
3616 render_post(post, index, actions, &state.directory, cx)
3617 }
3618 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
3619 Some(Row::LoadOlder) => {
3620 let view = env.view.clone();
3621 cx.defer(move |cx| {
3622 view.update(cx, |this, cx| this.request_older(cx)).ok();
3623 });
3624 h_flex()
3625 .w_full()
3626 .py_2()
3627 .gap(px(6.))
3628 .justify_center()
3629 .text_size(px(12.))
3630 .text_color(theme::text_muted())
3631 .child(icon(IconName::Loader, 12., theme::text_muted()))
3632 .child("Loading older messages")
3633 .into_any_element()
3634 }
3635 Some(Row::LoadNewer) => {
3636 let view = env.view.clone();
3637 cx.defer(move |cx| {
3638 view.update(cx, |this, cx| {
3639 this.request_window_page(WindowDirection::Forward, cx)
3640 })
3641 .ok();
3642 });
3643 h_flex()
3644 .w_full()
3645 .py_2()
3646 .gap(px(6.))
3647 .justify_center()
3648 .text_size(px(12.))
3649 .text_color(theme::text_muted())
3650 .child(icon(IconName::Loader, 12., theme::text_muted()))
3651 .child("Loading newer messages")
3652 .into_any_element()
3653 }
3654 Some(Row::Start(start)) => {
3655 let state = env.app.read(cx);
3656 v_flex()
3657 .w_full()
3658 .items_center()
3659 .gap(px(8.))
3660 .pt(px(32.))
3661 .pb(px(16.))
3662 .child(match start.user_id.as_deref() {
3663 Some(user_id) if is_bot_id(user_id) => bot_tile(
3664 &state.directory,
3665 &Face {
3666 user_id: Some(user_id.to_owned()),
3667 name: start.title.clone(),
3668 },
3669 56.,
3670 ),
3671 user_id => {
3672 person_avatar(&state.directory, user_id, &start.title, 56.)
3673 }
3674 })
3675 .child(
3676 div()
3677 .text_size(px(16.))
3678 .font_weight(FontWeight::SEMIBOLD)
3679 .text_color(theme::text())
3680 .child(start.title.clone()),
3681 )
3682 .child(
3683 div()
3684 .text_size(px(12.))
3685 .text_color(theme::text_muted())
3686 .child("This is the beginning of the conversation"),
3687 )
3688 .into_any_element()
3689 }
3690 None => div().into_any_element(),
3691 }
3692 },
3693 )
3694 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3695 .jump_button(!in_feed)
3696 .force_jump_button(detached)
3697 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3698 .with_jump_button_renderer(|button| {
3699 button
3700 .label(jump::JUMP_TO_NEWEST_LABEL)
3701 .tooltip(jump::jump_to_newest_tooltip())
3702 .border_0()
3703 .bg(theme::accent())
3704 .text_color(theme::on_accent())
3705 })
3706 .when(detached, |scroller| {
3707 let view = cx.weak_entity();
3708 scroller.on_jump(move |_, cx| {
3709 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
3710 })
3711 })
3712 .with_bottom_fade(background)
3713 .with_top_inset(timeline_top_inset);
3714
3715 root = match self.current.as_ref().filter(|_| !drafting) {
3716 Some(current) => {
3717 let tab_bar = self
3718 .render_tab_bar(window, cx)
3719 .or_else(|| self.render_meeting_tab_bar(cx));
3720 let (inline_tabs, tabs_row) = match tab_bar {
3721 Some(tabs) if self.tabs_below_title(window) => (None, Some(tabs)),
3722 tabs => (tabs, None),
3723 };
3724 root.child(self.render_header(current, inline_tabs, cx))
3725 .children(tabs_row.map(|tabs| {
3726 h_flex()
3727 .w_full()
3728 .h(px(TABS_ROW_HEIGHT))
3729 .flex_none()
3730 .px(px(HEADER_PADDING))
3731 .child(tabs)
3732 }))
3733 .child(edge_divider(HEADER_DIVIDER))
3734 }
3735 None => root.child(self.draft.clone()),
3736 };
3737 let sync_failed = self
3738 .current
3739 .as_ref()
3740 .is_some_and(|current| current.sync.failed);
3741 if let Some(notice) = &self.notice {
3742 root = root.child(
3743 h_flex()
3744 .px(px(20.))
3745 .py_1()
3746 .gap(px(8.))
3747 .items_center()
3748 .text_xs()
3749 .bg(theme::amber().opacity(0.15))
3750 .text_color(theme::amber())
3751 .child(div().flex_1().min_w_0().child(notice.clone()))
3752 .when(sync_failed, |bar| {
3753 bar.child(
3754 Button::new("retry-fetch")
3755 .ghost()
3756 .compact()
3757 .label("Retry")
3758 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
3759 )
3760 }),
3761 );
3762 }
3763 let recap_active = self.recap_active();
3764 let empty_channel = in_feed && self.rows.borrow().is_empty();
3765 let new_post = self.render_new_post(window, cx);
3766 self.watch_feed_scroll(cx);
3767 let feed_scrolled = new_post.is_some() && self.scroller.read(cx).is_scrolled_from_top();
3768 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
3769 let draft = self.draft.read(cx);
3770 let group_name = draft.group_name(cx);
3771 draft.render_empty(&self.app.read(cx).directory, &group_name)
3772 } else if self.shared_active() {
3773 self.render_shared(cx)
3774 } else if self.recap_active() {
3775 self.render_recap(cx)
3776 } else if empty_channel {
3777 div()
3778 .size_full()
3779 .flex()
3780 .items_center()
3781 .justify_center()
3782 .text_size(px(13.))
3783 .text_color(theme::text_muted())
3784 .child("No posts in this channel yet")
3785 .into_any_element()
3786 } else {
3787 scroller.into_any_element()
3788 };
3789 let channel_details = self.render_channel_details(cx);
3790 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3791 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3792 let content = v_flex()
3793 .relative()
3794 .flex_1()
3795 .min_w_0()
3796 .min_h_0()
3797 .children(new_post)
3798 .child(
3799 div()
3800 .debug_selector(|| TIMELINE_TAG.into())
3801 .relative()
3802 .flex_1()
3803 .min_h_0()
3804 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3805 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3806 .child(body)
3807 .when(feed_scrolled, |timeline| {
3808 timeline.child(
3809 edge_divider(FEED_EDGE_TAG)
3810 .absolute()
3811 .top_0()
3812 .left_0()
3813 .right_0(),
3814 )
3815 })
3816 .children(pin_banner.map(pin_banner_overlay)),
3817 )
3818 .children(self.render_draft_error(cx))
3819 .when(
3820 !in_feed && !recap_active,
3821 |column| match &forward_selection {
3822 Some(snapshot) => column.child(self.render_forward_footer(snapshot, cx)),
3823 None => column
3824 .child(self.render_typing_line(cx))
3825 .children(self.render_proposal_card(cx))
3826 .child(self.composer.clone()),
3827 },
3828 )
3829 .child(self.render_drop_overlay(cx));
3830 root.child(
3831 h_flex()
3832 .relative()
3833 .flex_1()
3834 .min_h_0()
3835 .w_full()
3836 .items_stretch()
3837 .child(content)
3838 .children(channel_details)
3839 .children(find_panel.map(|panel| {
3840 div()
3841 .h_full()
3842 .w(px(FIND_PANEL_WIDTH))
3843 .min_w_0()
3844 .flex_shrink(1.)
3845 .when(find_overlays, |slot| {
3846 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3847 })
3848 .child(panel)
3849 })),
3850 )
3851 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3852 if this.reaction_details.is_some() {
3853 this.close_reaction_details(cx);
3854 cx.stop_propagation();
3855 }
3856 }))
3857 .on_action(cx.listener(|this, _: &Escape, window, cx| {
3858 if this.draft_active {
3859 if this.draft.read(cx).has_focus(window, cx) {
3860 this.draft.update(cx, |draft, cx| draft.escape(cx));
3861 }
3862 } else if this.cancel_forward_selection(cx) {
3863 } else if !this.on_escape(window, cx) {
3864 cx.propagate();
3865 }
3866 }))
3867 .into_any_element()
3868 }
3869}
3870
3871fn typing_dots() -> impl IntoElement {
3872 h_flex()
3873 .gap(px(3.))
3874 .flex_none()
3875 .children((0..TYPING_DOT_COUNT).map(|index| {
3876 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
3877 div()
3878 .size(px(TYPING_DOT_SIZE))
3879 .rounded_full()
3880 .bg(theme::text_muted())
3881 .with_animation(
3882 ElementId::NamedInteger("typing-dot".into(), index as u64),
3883 Animation::new(TYPING_PULSE_PERIOD).repeat(),
3884 move |dot, delta| {
3885 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
3886 dot.opacity(0.3 + 0.7 * wave)
3887 },
3888 )
3889 }))
3890}
3891
3892fn record_width(width: &Rc<Cell<f32>>) -> impl IntoElement {
3893 let width = width.clone();
3894 canvas(
3895 move |bounds, window, _| {
3896 let measured = f32::from(bounds.size.width);
3897 if (measured - width.replace(measured)).abs() > 0.5 {
3898 window.request_animation_frame();
3899 }
3900 },
3901 |_, _, _, _| {},
3902 )
3903 .absolute()
3904 .top_0()
3905 .left_0()
3906 .size_full()
3907}
3908
3909fn progress_bar() -> impl IntoElement {
3910 div()
3911 .absolute()
3912 .left_0()
3913 .right_0()
3914 .bottom(px(-1.))
3915 .h(px(2.))
3916 .overflow_hidden()
3917 .bg(theme::border())
3918 .child(
3919 div()
3920 .absolute()
3921 .top_0()
3922 .h_full()
3923 .w(relative(PROGRESS_BAR_WIDTH))
3924 .bg(theme::own_read())
3925 .with_animation(
3926 "sync-progress",
3927 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
3928 |bar, delta| {
3929 let travel = 1. + PROGRESS_BAR_WIDTH;
3930 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
3931 bar.left(relative(
3932 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
3933 ))
3934 },
3935 ),
3936 )
3937}
3938
3939fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
3940 let (app, chat_id) = (app.clone(), chat_id.to_owned());
3941 Button::new("chat-add-people")
3942 .ghost()
3943 .compact()
3944 .icon(IconName::UserPlus)
3945 .tooltip("Add people")
3946 .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
3947 .into_any_element()
3948}
3949
3950#[cfg(test)]
3951mod tests {
3952 use std::sync::Arc;
3953
3954 use super::{DropTarget, drop_overlay_text};
3955
3956 use gpui_kit::test::TestWindowExt as _;
3957 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
3958 use store::Store;
3959
3960 use super::ConversationView;
3961 use crate::app_state::{AppState, Mode, Selection};
3962
3963 #[test]
3964 fn chat_overlay_names_the_chat_and_the_onedrive() {
3965 assert_eq!(
3966 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
3967 (
3968 "Drop to attach to Mara Lin".to_owned(),
3969 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
3970 )
3971 );
3972 }
3973
3974 #[test]
3975 fn channel_overlay_points_to_the_channel_files() {
3976 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
3977 assert_eq!(
3978 detail,
3979 "1 file. Images go into the message, other files to the channel's Files."
3980 );
3981 }
3982
3983 #[test]
3984 fn new_chat_overlay_says_files_wait_for_the_chat() {
3985 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
3986 assert_eq!(heading, "Drop to attach to the new chat");
3987 assert_eq!(
3988 detail,
3989 "2 files. Images go into the message. Files can be added once the chat exists."
3990 );
3991 }
3992
3993 #[gpui_kit::test]
3994 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
3995 cx.update(gpui_kit::init);
3996 let store = Arc::new(Store::open_in_memory().unwrap());
3997 crate::demo::seed(&store);
3998 let mode = Mode {
3999 demo: true,
4000 read_only: false,
4001 demo_sync: None,
4002 };
4003 let (handle, app, _view) = cx.update(|cx| {
4004 let app = cx.new(|_| {
4005 let mut state = AppState::new(store, mode);
4006 crate::demo::seed_directory(&mut state);
4007 state.selection = Some(crate::demo::first_selection());
4008 state
4009 });
4010 let shared = app.clone();
4011 let (handle, view) =
4012 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4013 cx.new(|cx| ConversationView::new(shared, window, cx))
4014 })
4015 .unwrap();
4016 (handle, app, view)
4017 });
4018 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4019 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
4020 cx.update_window(handle, move |_, window, cx| {
4021 run(window, cx);
4022 window.render_frame(cx);
4023 })
4024 .unwrap();
4025 };
4026 step(cx, |window, cx| window.render_frame(cx));
4027 step(cx, |window, cx| window.input("lea", cx));
4028 step(cx, |window, cx| window.press("enter", cx));
4029 step(cx, |window, cx| window.press("enter", cx));
4030 step(cx, |window, cx| window.input("Hello Lea", cx));
4031 step(cx, |window, cx| window.press("enter", cx));
4032 cx.update(|cx| {
4033 let state = app.read(cx);
4034 assert!(!state.new_chat);
4035 assert_eq!(
4036 state.selection,
4037 Some(Selection::Chat("demo-chat-new-1".to_owned()))
4038 );
4039 let chat = state
4040 .sidebar
4041 .chats
4042 .iter()
4043 .find(|chat| chat.id == "demo-chat-new-1")
4044 .expect("new chat in the sidebar");
4045 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
4046 });
4047 }
4048
4049 #[gpui_kit::test]
4050 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
4051 cx.update(gpui_kit::init);
4052 let store = Arc::new(Store::open_in_memory().unwrap());
4053 crate::demo::seed(&store);
4054 let mode = Mode {
4055 demo: true,
4056 read_only: false,
4057 demo_sync: None,
4058 };
4059 let (handle, app) = cx.update(|cx| {
4060 let app = cx.new(|_| {
4061 let mut state = AppState::new(store, mode);
4062 crate::demo::seed_directory(&mut state);
4063 state.selection = Some(crate::demo::first_selection());
4064 state
4065 });
4066 let shared = app.clone();
4067 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4068 cx.new(|cx| ConversationView::new(shared, window, cx))
4069 })
4070 .unwrap();
4071 (handle, app)
4072 });
4073 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4074 cx.update_window(handle, |_, window, cx| {
4075 window.render_frame(cx);
4076 window.press("escape", cx);
4077 window.render_frame(cx);
4078 window.press("escape", cx);
4079 window.render_frame(cx);
4080 })
4081 .unwrap();
4082 cx.update(|cx| {
4083 let state = app.read(cx);
4084 assert!(!state.new_chat);
4085 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4086 });
4087 }
4088}