BlueGit

ict rusty-teams

Files

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

conversation.rs

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