BlueGit

ict rusty-teams

Files

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

conversation.rs

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