BlueGit

ict rusty-teams

Files

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

conversation.rs

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