BlueGit

ict rusty-teams

Files

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

conversation.rs

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