BlueGit

ict rusty-teams

Files

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

conversation.rs

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