BlueGit

ict rusty-teams

Files

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

conversation.rs

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