BlueGit

ict rusty-teams

Files

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

conversation.rs

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