BlueGit

ict rusty-teams

Files

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

conversation.rs

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