BlueGit

ict rusty-teams

Files

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

conversation.rs

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