BlueGit

ict rusty-teams

Files

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

conversation.rs

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