BlueGit

ict rusty-teams

Files

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

conversation.rs

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