use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet, VecDeque}; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::time::{Duration, Instant}; use chrono::{DateTime, Local, Utc}; use gpui_kit::assets::IconName; use gpui_kit::component::{ button::{Button, ButtonVariants as _}, h_flex, input::{Escape, InputState}, message_scroller::{MessageScroller, MessageScrollerState}, tooltip::Tooltip, v_flex, }; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; use store::{ChannelTabRecord, MessageRecord, OutboxState, OutboxTarget, is_bot_id}; use teams_core::{ ExecuteAction, FileCard, ImageRef, JumpPlan, LinkPreview, WindowDirection, is_notes_chat, without_islands, }; mod channel_details; pub(crate) mod chat_header_actions; mod copilot; pub use channel_details::{ CHANNEL_DETAILS_BUTTON, CHANNEL_DETAILS_PINNED_TAG, CHANNEL_DETAILS_SHARED_TAG, CHANNEL_DETAILS_TAG, }; mod deletes; mod detached; mod feed; mod forward_select; #[cfg(test)] pub use forward_select::{ FORWARD_FOOTER_BAR_TAG, FORWARD_FOOTER_COUNT_TAG, FORWARD_FOOTER_NEXT_TAG, FORWARD_FOOTER_TAG, }; mod absence; mod appear_tracker; mod jump; mod notes_space; mod pins; mod proposal; mod recap; mod receipt_fade; mod render_env; mod scheduled; mod shared; use super::add_people_dialog::open_add_people; use super::attachments::FileActions; use super::avatar::{ bot_tile, member_stack, person_avatar, spec_avatar, team_avatar, with_presence, }; use super::call_controls::header_call_controls; use super::channel_tabs::{ChannelPane, HEADER_TITLE_MAX_WIDTH}; use super::chat_members::members_popover; use super::chat_pop_out; use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview}; use super::find_panel::{FIND_PANEL_WIDTH, FindPanel, FindPanelEvent}; use super::group_name::{GroupNameSlot, group_name_button}; use super::message_actions::{Action, DelegateEntry, MessageMenu}; use super::message_context_menu::OpenContextMenu; use super::message_row::{ AVATAR_GAP, AVATAR_SIZE, JUMP_HIGHLIGHT_PERIOD, render_message_row, render_skeleton_row, }; use super::new_chat::{NewChatDraft, NewChatEvent, Pick, composer_placeholder}; use super::pin_banner::{pin_banner_inset, pin_banner_overlay}; use super::post_card::render_post; use super::profile_card::opens_profile; use super::reaction_picker::{PickHandler, ReactionPicker}; use super::reaction_pills::{ReactionControls, ReactionPopover}; use super::scroll_edge::edge_divider; use super::toolbar_placement::{TimelineBounds, record_bounds}; use super::widgets::{icon, symbol}; use crate::agents::{AgentRun, StartRequest}; use crate::app_state::{AppEvent, AppState, Selection, selection_title}; use crate::backend::Engine; use crate::card_state::CardScope; use crate::channel_files::DownloadSource; use crate::chat_settings_actions::shown_receipt; use crate::data::{existing_one_on_one, is_one_on_one, one_on_one_bot, others}; use crate::demo_library::DemoLibrary; use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget}; use crate::emoji; use crate::emoticons; use crate::i18n::tr; use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of}; use crate::notice::short_error; use crate::outbox::{Delivered, deliver, new_outbox_id, outbox_record, outgoing_of}; use crate::pending_rows::pending_row; use crate::people::{local_names, resolve_names}; use crate::reaction_model::UNKNOWN_REACTOR; use crate::read_state::{ReadTrigger, missed_before_fetch, plan_read}; use crate::rows::{ Delivery, LocalImage, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction, apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows, forward_sender_ids, has_own_reaction, message_draft, message_text, own_reaction_glyph, place_local_rows, placeholder_rows, reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows, }; use crate::runtime; use crate::scheduled_rows::SCHEDULED_KEY_PREFIX; use crate::sidebar_model::{AvatarSpec, Face, channel_unread}; use crate::theme; use crate::translation::TranslationLine; use crate::typing::typing_tooltip; use app_ui_kit::layout::{COMFY_RUNWAY_WIDTH, ISLAND_GAP, RAIL_WIDTH, SIDEBAR_WIDTH}; use detached::DetachedWindow; use feed::{FeedStash, subject_input}; use mcp::ReactionProposal; use render_env::RenderEnv; use shared::SharedState; pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button"; pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header"; pub const TIMELINE_TAG: &str = "shell/islands/main/timeline"; pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed"; const SENT_PREVIEWS_KEPT: usize = 16; const HOVER_LEAVE_GRACE: Duration = Duration::from_millis(250); const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner."; const QUIET_RETRY_DELAYS: [Duration; 3] = [ Duration::from_secs(2), Duration::from_secs(5), Duration::from_secs(15), ]; const HEADER_HEIGHT: f32 = 60.; const HEADER_PADDING: f32 = 20.; const HEADER_GAP: f32 = 12.; const HEADER_COMPACT_GAP: f32 = 4.; const POP_IN_BUTTON_SIZE: f32 = 32.; const HEADER_LEAD_SIZE: f32 = 36.; const TABS_INLINE_MIN_WIDTH: f32 = 560.; const FIND_MIN_TIMELINE_WIDTH: f32 = 360.; const TABS_ROW_HEIGHT: f32 = 36.; const CHAT_OPEN_LIMIT: usize = 60; const CHANNEL_OPEN_LIMIT: usize = 300; const GROWTH_HEADROOM: usize = 20; const META_USER_ID: &str = "me_user_id"; const PENDING_KEY_PREFIX: &str = "pending-"; const DEMO_DOWNLOAD_STEPS: u8 = 10; const DEMO_DOWNLOAD_STEP: Duration = Duration::from_millis(100); const JUMP_SCAN_LIMIT: usize = 5000; const JUMP_CONTEXT_MESSAGES: usize = 12; const PROGRESS_DELAY: Duration = Duration::from_millis(400); const SLOW_AFTER: Duration = Duration::from_secs(8); const PROGRESS_MIN_VISIBLE: Duration = Duration::from_millis(500); const PROGRESS_BAR_PERIOD: Duration = Duration::from_millis(1400); const PROGRESS_BAR_WIDTH: f32 = 0.35; const TYPING_BUBBLE_HEIGHT: f32 = 28.; const TYPING_BUBBLE_PADDING: f32 = 12.; const TYPING_SIDE_INSET: f32 = 20.; const COMPOSER_TOP_GAP: f32 = 16.; const TYPING_TOP_GAP: f32 = 16.; const TYPING_BOTTOM_GAP: f32 = 8.; pub const TYPING_TAG: &str = "shell/islands/main/typing"; const TYPING_DOT_SIZE: f32 = 5.; const TYPING_DOT_COUNT: usize = 3; const TYPING_PULSE_PERIOD: Duration = Duration::from_millis(1200); #[derive(Clone, Copy)] enum HoverSlot { Row, Toolbar, } /// Where the pointer is right now. A move from a row onto its toolbar reports the toolbar /// enter before the row leave, so a leave only starts the grace when neither part holds it. #[derive(Default)] struct PointerOn { row: Option, toolbar: Option, } impl PointerOn { fn slot(&mut self, slot: HoverSlot) -> &mut Option { match slot { HoverSlot::Row => &mut self.row, HoverSlot::Toolbar => &mut self.toolbar, } } fn holds(&self, key: &str) -> bool { self.row.as_deref() == Some(key) || self.toolbar.as_deref() == Some(key) } } #[derive(Debug, Clone, PartialEq, Eq)] enum ViewMode { Flat, ThreadList, Thread(String), } #[derive(Default)] struct SyncProgress { messages: bool, receipts: bool, empty_cache: bool, newest_cached: Option>, started_at: DateTime, shown_at: Option, slow: bool, failed: bool, } impl SyncProgress { fn running(&self) -> bool { self.messages || self.receipts } } struct Current { selection: Selection, title: String, mode: ViewMode, loaded_limit: usize, loaded_count: usize, has_older: bool, loading_older: bool, older_blocked: bool, quiet_retries: usize, fetched: bool, first_unread: Option, posts_new_after: Option>, sync: SyncProgress, detached: Option, window_request: Option, } struct ReactionDetails { message_key: String, anchor_glyph: String, tab: Option, } #[derive(Clone, Copy, PartialEq, Eq)] enum ReactionAttempt { Acted, Started, AlreadyThere, MissingMessage, Blocked, } pub struct ConversationView { app: Entity, pinned: bool, popped_out: bool, scroller: Entity, composer: Entity, subject: Entity, new_post_open: bool, reply_composer: Option>, reply_root: Option, reply_drafts: HashMap, feed_stash: Option, feed_rows_seen: Rc>, feed_at_top: bool, older_anchor: Option, draft: Entity, draft_active: bool, draft_created: Option<(Vec, String)>, draft_error: Option, rows: Rc>>, current: Option, pending: Vec, saving_edits: HashSet, pending_counter: usize, pending_outgoing: HashMap, sent_previews: VecDeque<(String, Vec)>, pending_reactions: PendingReactions, downloads: Downloads, hovered_message: Option, hover_leave_serial: u64, pointer_on: PointerOn, toolbar_hovered: Option, context_menu: Option, context_serial: u64, timeline_bounds: TimelineBounds, typing_offset: Cell, header_width: Rc>, toolbar_pinned: Option, toolbar_suppressed: Option, recent: Entity, picker: Entity, reaction_details: Option, highlighted_message: Option, fetched_jump: Option, loading_post: Option, pin_index: usize, channel_details_open: bool, copilot: copilot::CopilotPane, pinned_posts_expanded: bool, channel_details_scroll: ScrollHandle, scroller_watch: Option<(EntityId, Subscription)>, pin_previews: HashMap, pin_fetches: HashSet, notice: Option, scheduled_failure: Option, scheduled_in_flight: HashSet, drag_file_count: usize, sync_generation: u64, rebuild_generation: u64, window_active: bool, pane: ChannelPane, recap: recap::RecapState, recap_search: Entity, channel_tabs: Vec, tab_links: HashMap, focus_handle: FocusHandle, shared: SharedState, demo_library: DemoLibrary, new_folder_input: Option>, agent_layouts: HashMap, agent_runs: Rc>>, reaction_proposals: Rc>>, receipt_fade: receipt_fade::ReceiptFade, appear_tracker: appear_tracker::AppearTracker, find_panel: Option>, find_subscription: Option, group_name: GroupNameSlot, _subscriptions: Vec, } struct RebuildPlan { conversation_id: String, is_chat: bool, mode: ViewMode, limit: usize, loading_post: bool, thread_root: Option, window: Option<(DateTime, DateTime, bool, bool)>, syncing_messages: bool, older_blocked: bool, can_load_older: bool, start: Option, } struct LoadedRecords { records: Vec, sync_has_more: bool, } struct BuiltRows { rows: Vec, has_older: bool, placeholders: bool, } fn load_records(store: &store::Store, plan: &RebuildPlan) -> LoadedRecords { let sync_state = store.sync_state(&plan.conversation_id).ok().flatten(); let records = match (&plan.thread_root, plan.window) { (Some(root_id), _) => store .thread_messages(&plan.conversation_id, root_id) .unwrap_or_default(), (None, Some((oldest, newest, _, _))) => store .messages_between(&plan.conversation_id, oldest, newest) .unwrap_or_default(), (None, None) if plan.is_chat => without_islands( store .messages(&plan.conversation_id, None, plan.limit) .unwrap_or_default(), sync_state.as_ref().and_then(|state| state.oldest_loaded), ), (None, None) => store .messages(&plan.conversation_id, None, plan.limit) .unwrap_or_default(), }; LoadedRecords { records, sync_has_more: sync_state.as_ref().is_none_or(|state| state.has_more), } } fn build_rows(plan: &RebuildPlan, loaded: &LoadedRecords, context: &RowContext) -> BuiltRows { let records = &loaded.records; let has_older = loaded.sync_has_more && !plan.older_blocked && plan.can_load_older; let placeholders = records.is_empty() && (plan.loading_post || plan.syncing_messages && plan.thread_root.is_none()); if placeholders { return BuiltRows { rows: placeholder_rows(), has_older: false, placeholders, }; } let (rows, has_older) = match &plan.mode { ViewMode::Flat => match plan.window { Some((_, _, has_older_window, has_newer_window)) => { let mut rows = flat_rows(records, context, has_older_window); if has_newer_window { rows.push(Row::LoadNewer); } (rows, has_older_window) } None => { let mut rows = flat_rows(records, context, has_older); if !has_older && let Some(start) = plan.start.clone() { rows.insert(0, Row::Start(start)); } (rows, has_older) } }, ViewMode::ThreadList => (thread_list_rows(records, context, has_older), has_older), ViewMode::Thread(root_id) => (thread_rows(records, root_id, context), false), }; BuiltRows { rows, has_older, placeholders, } } fn open_limit(selection: &Selection) -> usize { match selection { Selection::Chat(_) => CHAT_OPEN_LIMIT, Selection::Channel(_) => CHANNEL_OPEN_LIMIT, } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum DropTarget { Chat, Channel, Library, NewChat, } fn drop_overlay_text(title: &str, target: DropTarget, count: usize) -> (String, String) { let files = if count == 1 { "1 file".to_owned() } else { format!("{count} files") }; match target { DropTarget::Chat => ( format!("Drop to attach to {title}"), format!("{files}. Images go into the message, other files to your OneDrive."), ), DropTarget::Channel => ( format!("Drop to attach to {title}"), format!("{files}. Images go into the message, other files to the channel's Files."), ), DropTarget::Library => ( format!("Drop to upload to {title}"), format!("{files}. Files go into the folder you have open."), ), DropTarget::NewChat => ( "Drop to attach to the new chat".to_owned(), format!( "{files}. Images go into the message. Files can be added once the chat exists." ), ), } } fn shown_in_view(mode: &ViewMode, record: &store::OutboxRecord) -> bool { match mode { ViewMode::Flat => record.target == OutboxTarget::Flat, ViewMode::ThreadList => matches!(record.target, OutboxTarget::Post | OutboxTarget::Thread), ViewMode::Thread(root_id) => { record.target == OutboxTarget::Thread && record.thread_root_id.as_deref() == Some(root_id.as_str()) } } } enum DownloadEvent { Progress(u8), Finished(Result), } async fn save_file( engine: &Engine, card: &FileCard, source: &DownloadSource, events: &tokio::sync::mpsc::UnboundedSender, ) -> Result { let mut part = PartFile::create(&downloads::downloads_directory(), &card.name) .map_err(|error| short_error(&error))?; let write = |bytes: &[u8]| part.write(bytes); let progress = |percent| { let _ = events.send(DownloadEvent::Progress(percent)); }; match source { DownloadSource::Share => engine.download_file(&card.open_url, write, progress).await, DownloadSource::Library(file) => engine.download_library_file(file, write, progress).await, } .map_err(|error| short_error(&error))?; part.finish().map_err(|error| short_error(&error)) } impl ConversationView { fn file_actions( &self, message_key: &str, files: &[FileCard], view: WeakEntity, ) -> FileActions { let conversation_id = self.conversation_id().unwrap_or_default(); let (key, cards) = (message_key.to_owned(), files.to_vec()); let open_urls: Vec<&str> = files.iter().map(|card| card.open_url.as_str()).collect(); FileActions { states: self .downloads .states_for(&conversation_id, message_key, &open_urls), activate: Rc::new(move |index, cx| { let Some(card) = cards.get(index).cloned() else { return; }; let key = key.clone(); let conversation_id = conversation_id.clone(); view.update(cx, |this, cx| { this.activate_file(&conversation_id, &key, card, DownloadSource::Share, cx) }) .ok(); }), } } fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context) { let Some(current) = self.current.as_ref() else { return; }; let now = Local::now(); let items = collect_gallery( &self.rows.borrow(), now.date_naive(), app_base::format::Zone::Local, ); let Some(index) = position_of(&items, message_key, url) else { return; }; let request = ViewerRequest { conversation_id: current.selection.conversation_id().to_owned(), conversation_title: selection_title(&self.app.read(cx).sidebar, ¤t.selection), items, index, }; self.app .update(cx, |state, cx| state.request_image_viewer(request, cx)); } /// Downloads a Teams video clip into the image cache, then opens it in the system player. fn play_clip(&mut self, url: String, cx: &mut Context) { let Some(engine) = self.app.read(cx).engine.clone() else { return; }; let clip = ImageRef { id: url.clone(), url, width: None, height: None, alt: None, }; let fetched = runtime::spawn(async move { engine.fetch_image(&clip).await }); cx.spawn(async move |this, cx| { let Ok(outcome) = fetched.await else { return; }; this.update(cx, |this, cx| match outcome { Ok(Some(path)) => cx.open_with_system(&path), Ok(None) => {} Err(error) => this.show_notice( &format!("Could not play the video: {}", short_error(&error)), cx, ), }) .ok(); }) .detach(); } fn activate_file( &mut self, conversation_id: &str, message_key: &str, card: FileCard, source: DownloadSource, cx: &mut Context, ) { let key = DownloadKey::new(conversation_id, message_key, &card.open_url); match downloads::click_action(self.downloads.state(&key)) { ClickAction::Ignore => {} ClickAction::Start => self.start_download(key, card, source, cx), ClickAction::Reveal(path) => { let folder = path .parent() .map(Path::to_path_buf) .unwrap_or_else(downloads::downloads_directory); match downloads::reveal_target(&path, path.exists(), folder) { RevealTarget::File(path) => downloads::reveal_in_file_manager(&path), RevealTarget::Folder(folder) => cx.open_with_system(&folder), } } } } fn start_download( &mut self, key: DownloadKey, card: FileCard, source: DownloadSource, cx: &mut Context, ) { if !self.downloads.begin(&key) { return; } cx.notify(); let state = self.app.read(cx); let (demo, engine) = (state.mode.demo, state.engine.clone()); let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::(); if demo { cx.spawn(async move |this, cx| { for step in 1..=DEMO_DOWNLOAD_STEPS { cx.background_executor().timer(DEMO_DOWNLOAD_STEP).await; let percent = (u32::from(step) * 100 / u32::from(DEMO_DOWNLOAD_STEPS)) as u8; let progressed = this.update(cx, |this, cx| { this.downloads.set_progress(&key, percent); cx.notify(); }); if progressed.is_err() { return; } } let outcome = downloads::write_demo_file(&card.name).map_err(|error| short_error(&error)); this.update(cx, |this, cx| { this.downloads.finish(&key, outcome); cx.notify(); }) .ok(); }) .detach(); return; } let Some(engine) = engine else { self.downloads.finish(&key, Err("not connected".to_owned())); return; }; drop(runtime::spawn(async move { let outcome = save_file(&engine, &card, &source, &sender).await; let _ = sender.send(DownloadEvent::Finished(outcome)); })); cx.spawn(async move |this, cx| { while let Some(event) = receiver.recv().await { let updated = this.update(cx, |this, cx| { match event { DownloadEvent::Progress(percent) => { this.downloads.set_progress(&key, percent) } DownloadEvent::Finished(outcome) => this.downloads.finish(&key, outcome), } cx.notify(); }); if updated.is_err() { break; } } }) .detach(); } pub fn new(app: Entity, window: &mut Window, cx: &mut Context) -> Self { Self::build(app, None, window, cx) } pub fn pinned_to( app: Entity, selection: Selection, window: &mut Window, cx: &mut Context, ) -> Self { Self::build(app, Some(selection), window, cx) } pub fn popped_out( app: Entity, selection: Selection, window: &mut Window, cx: &mut Context, ) -> Self { let mut view = Self::build(app, Some(selection), window, cx); view.popped_out = true; view } fn build( app: Entity, pinned: Option, window: &mut Window, cx: &mut Context, ) -> Self { let scroller = cx.new(|cx| MessageScrollerState::new(0, cx)); let composer = cx.new(|cx| Composer::new(app.clone(), window, cx)); let subject = subject_input(window, cx); let recap_search = recap::search_input(window, cx); let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store)); let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx)); let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx)); let mut subscriptions = vec![ cx.subscribe_in(&app, window, Self::on_app_event), cx.observe(&app, |_, _, cx| cx.notify()), cx.subscribe_in(&composer, window, Self::on_composer_event), cx.subscribe_in(&draft, window, Self::on_draft_event), cx.subscribe_in(&subject, window, Self::on_subject_event), cx.subscribe_in(&recap_search, window, Self::on_recap_search_event), cx.observe_window_activation(window, Self::on_window_activation), cx.on_app_quit(|this, cx| { this.composer .update(cx, |composer, cx| composer.save_draft_now(cx)); async {} }), cx.observe_keystrokes(|this, event, _, cx| { if event.keystroke.key == "escape" { this.close_reaction_details(cx); this.close_context_menu(false, cx); } }), ]; if let Some(runs) = crate::agents::runs_handle(cx) { subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx))); } if let Some(api) = crate::agent_api::handle(cx) { subscriptions.push(cx.observe(&api, |this, _, cx| this.sync_reaction_pills(cx))); } let mut view = ConversationView { group_name: GroupNameSlot::default(), app, pinned: pinned.is_some(), popped_out: false, scroller, composer, subject, new_post_open: false, reply_composer: None, reply_root: None, reply_drafts: HashMap::new(), feed_stash: None, feed_rows_seen: Rc::new(Cell::new(usize::MAX)), feed_at_top: true, older_anchor: None, draft, draft_active: false, draft_created: None, draft_error: None, rows: Rc::new(RefCell::new(Vec::new())), current: None, pending: Vec::new(), saving_edits: HashSet::new(), pending_counter: 0, pending_outgoing: HashMap::new(), sent_previews: VecDeque::new(), pending_reactions: HashMap::new(), downloads: Downloads::default(), hovered_message: None, hover_leave_serial: 0, pointer_on: PointerOn::default(), toolbar_hovered: None, context_menu: None, context_serial: 0, timeline_bounds: TimelineBounds::default(), typing_offset: Cell::new(TYPING_BOTTOM_GAP), header_width: Rc::default(), toolbar_pinned: None, toolbar_suppressed: None, recent, picker, reaction_details: None, highlighted_message: None, fetched_jump: None, loading_post: None, pin_index: 0, channel_details_open: false, copilot: copilot::CopilotPane::default(), pinned_posts_expanded: false, channel_details_scroll: ScrollHandle::new(), scroller_watch: None, pin_previews: HashMap::new(), pin_fetches: HashSet::new(), notice: None, scheduled_failure: None, scheduled_in_flight: HashSet::new(), drag_file_count: 0, sync_generation: 0, rebuild_generation: 0, window_active: window.is_window_active(), pane: ChannelPane::Posts, recap: recap::RecapState::default(), recap_search, channel_tabs: Vec::new(), tab_links: HashMap::new(), focus_handle: cx.focus_handle(), shared: SharedState::default(), demo_library: DemoLibrary::default(), new_folder_input: None, agent_layouts: HashMap::new(), agent_runs: Rc::new(RefCell::new(HashMap::new())), reaction_proposals: Rc::new(RefCell::new(HashMap::new())), receipt_fade: receipt_fade::ReceiptFade::default(), appear_tracker: appear_tracker::AppearTracker::default(), find_panel: None, find_subscription: None, _subscriptions: subscriptions, }; if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) { view.open(selection, window, cx); } view } #[cfg_attr(not(windows), allow(dead_code))] pub fn composer_is_empty(&self, cx: &App) -> bool { self.composer.read(cx).is_empty(cx) } #[cfg_attr(not(windows), allow(dead_code))] pub fn opening_title(&self) -> Option { let loading = self .rows .borrow() .iter() .any(|row| matches!(row, Row::Skeleton(_))); self.current .as_ref() .filter(|_| loading) .map(|current| current.title.clone()) } pub fn send_in_flight(&self) -> bool { self.pending .iter() .any(|row| matches!(row.delivery, Delivery::Sending)) } fn on_window_activation(&mut self, window: &mut Window, cx: &mut Context) { self.window_active = window.is_window_active(); self.mark_read(ReadTrigger::Activation, cx); } fn on_app_event( &mut self, _: &Entity, event: &AppEvent, window: &mut Window, cx: &mut Context, ) { match event { AppEvent::Selection if self.pinned => {} AppEvent::Selection => { self.reaction_details = None; let (new_chat, selection) = { let state = self.app.read(cx); (state.new_chat, state.selection.clone()) }; if new_chat { self.enter_draft(window, cx); return; } if self.draft_active { let created = self .draft_created .as_ref() .map(|(_, chat_id)| chat_id.clone()); if let Some(chat_id) = created { self.composer .update(cx, |composer, _| composer.carry_images_into(chat_id)); } self.leave_draft(window, cx); } match selection { Some(selection) => self.open(selection, window, cx), None => { self.current = None; self.rebuild(true, cx); } } } AppEvent::Messages(conversation_id) => { let is_current = self .current .as_ref() .is_some_and(|current| current.selection.conversation_id() == conversation_id); if is_current { if self.shared_active() || self.recap_active() || self.channel_details_open { self.refresh_shared_items(cx); } self.rebuild_in_background(cx); self.mark_read(ReadTrigger::Incoming, cx); self.on_pins_changed(conversation_id, cx); } } AppEvent::Images(keys) => self.remeasure_images(keys, cx), AppEvent::Cards(conversation_id) => self.refresh_cards(conversation_id, cx), AppEvent::Jump => self.apply_pending_jump(cx), AppEvent::Status => { if let Some(current) = self.current.as_mut() && current.sync.failed { current.fetched = false; } self.start_fetch(cx) } AppEvent::Directory => { self.refresh_reactor_names(cx); cx.notify(); } AppEvent::ForwardSelection => self.on_forward_selection_changed(window, cx), AppEvent::TaskDialog | AppEvent::LocalPreviews | AppEvent::Forward | AppEvent::ImageViewer | AppEvent::StatusMessage | AppEvent::CalendarEventPeek | AppEvent::Settings(_) | AppEvent::Profile | AppEvent::CallHistory | AppEvent::Ring | AppEvent::Activity | AppEvent::MissedCall(_) | AppEvent::MeetingReminder | AppEvent::MeetingChime | AppEvent::CallTone(_) | AppEvent::SoundSettings | AppEvent::FollowedStatus { .. } | AppEvent::OrgMessage(_) | AppEvent::Call => {} AppEvent::LiveMeeting => cx.notify(), AppEvent::Saved => cx.notify(), AppEvent::Translation | AppEvent::ChatSettings => self.rebuild(false, cx), AppEvent::Pins(conversation_id) => self.on_pins_changed(conversation_id, cx), AppEvent::Typing => cx.notify(), AppEvent::Scheduled => self.rebuild(false, cx), AppEvent::Outbox(conversation_id) => { let is_current = self .current .as_ref() .is_some_and(|current| current.selection.conversation_id() == conversation_id); if is_current { self.reload_pending(cx); self.rebuild(false, cx); } } AppEvent::Sidebar => { self.reload_channel_tabs(cx); self.mark_read(ReadTrigger::Incoming, cx); self.refresh_reactor_names(cx); if self.draft_active { self.on_draft_changed(window, cx); } else if let Some(current) = self.current.as_mut() { let title = selection_title(&self.app.read(cx).sidebar, ¤t.selection); if current.title != title { current.title = title; cx.notify(); } } } } } fn on_composer_event( &mut self, _: &Entity, event: &ComposerEvent, window: &mut Window, cx: &mut Context, ) { self.report_composer_activity(event, cx); match event { ComposerEvent::Submit(outgoing) => self.submit_main((**outgoing).clone(), window, cx), ComposerEvent::Schedule { outgoing, send_at } => { self.schedule((**outgoing).clone(), *send_at, window, cx) } ComposerEvent::EditLast => self.edit_last_own(window, cx), ComposerEvent::FocusMessages => window.focus(&self.focus_handle, cx), ComposerEvent::Typing(active) => self.send_typing(*active, cx), ComposerEvent::Edited => {} ComposerEvent::ClosePost => self.cancel_new_post(window, cx), ComposerEvent::RestorePost(subject) => { self.restore_new_post(subject.clone(), window, cx) } } } fn submit_main(&mut self, mut outgoing: Outgoing, window: &mut Window, cx: &mut Context) { if self.draft_active { return self.send_new_chat(outgoing, window, cx); } let in_feed = self.in_feed(); if in_feed && outgoing.edit.is_none() { outgoing.subject = self.take_subject(window, cx); } if in_feed { self.close_new_post(cx); } match &outgoing.edit { Some(edit) if edit.scheduled.is_some() => { self.send_scheduled_edit(outgoing, window, cx) } Some(_) => self.send_edit(outgoing, window, cx), None => self.send(outgoing, window, cx), } } fn typing_root(&self) -> Option { match self.current.as_ref().map(|current| ¤t.mode) { Some(ViewMode::Thread(root_id)) => Some(root_id.clone()), _ => None, } } fn send_typing(&self, active: bool, cx: &App) { self.send_typing_in(self.typing_root(), active, cx); } fn send_typing_in(&self, thread_root_id: Option, active: bool, cx: &App) { let state = self.app.read(cx); if state.mode.demo || state.mode.read_only || self.draft_active { return; } let (Some(engine), Some(conversation_id)) = (state.engine.clone(), self.conversation_id()) else { return; }; drop(runtime::spawn(async move { let sent = engine .send_typing(&conversation_id, thread_root_id.as_deref(), active) .await; if let Err(error) = sent && cfg!(debug_assertions) { crate::diagnostics::record(format!("typing indicator not sent: {error}")); } })); } fn stop_typing(&mut self, cx: &mut Context) { if self .composer .update(cx, |composer, _| composer.stop_typing()) { self.send_typing(false, cx); } } fn render_typing_line(&self, cx: &App) -> Option { if self.in_feed() { return None; } let app = self.app.read(cx); let faces = self .current .as_ref() .filter(|_| !self.draft_active) .map(|current| app.typing.faces(current.selection.conversation_id())) .unwrap_or_default(); if faces.is_empty() { return None; } let tooltip_text = typing_tooltip( &faces .iter() .map(|face| face.name.clone()) .collect::>(), ); let faces_element = match faces.as_slice() { [face] => person_avatar( &app.directory, face.user_id.as_deref(), &face.name, AVATAR_SIZE, ), _ => member_stack(&app.directory, &faces, faces.len(), true).into_any_element(), }; Some( h_flex() .debug_selector(|| TYPING_TAG.into()) .h(px(TYPING_BUBBLE_HEIGHT)) .px(px(TYPING_SIDE_INSET)) .gap(px(AVATAR_GAP)) .items_center() .child( div() .id("typing-faces") .flex_none() .tooltip(move |window, cx| { Tooltip::new(tooltip_text.clone()).build(window, cx) }) .child(faces_element), ) .child( h_flex() .h_full() .px(px(TYPING_BUBBLE_PADDING)) .items_center() .rounded_full() .bg(theme::surface_raised()) .child(typing_dots()), ) .into_any_element(), ) } fn open(&mut self, selection: Selection, window: &mut Window, cx: &mut Context) { if self .find_panel .as_ref() .is_some_and(|panel| panel.read(cx).selection() != &selection) { self.find_panel = None; self.find_subscription = None; } self.stop_typing(cx); self.stop_reply_typing(cx); let next_conversation_id = selection.conversation_id().to_owned(); self.composer.update(cx, |composer, cx| { composer.leave_conversation(&next_conversation_id, cx) }); self.close_new_post(cx); self.feed_stash = None; self.feed_at_top = true; self.restore_subject(None, window, cx); self.toolbar_hovered = None; self.reset_copilot(); crate::inline_video::stop(cx); self.toolbar_pinned = None; self.toolbar_suppressed = None; self.context_menu = None; self.agent_layouts.clear(); self.agent_runs.borrow_mut().clear(); self.reaction_proposals.borrow_mut().clear(); let title = selection_title(&self.app.read(cx).sidebar, &selection); let mode = match selection { Selection::Chat(_) => ViewMode::Flat, Selection::Channel(_) => ViewMode::ThreadList, }; let first_unread = self.first_unread_id(&selection, cx); let posts_new_after = self.channel_read_until(&selection, cx); self.current = Some(Current { loaded_limit: open_limit(&selection), selection, title, mode, loaded_count: 0, has_older: false, loading_older: false, older_blocked: false, fetched: false, quiet_retries: 0, first_unread, posts_new_after, sync: SyncProgress::default(), detached: None, window_request: None, }); self.refresh_agent_runs(cx); self.refresh_reaction_pills(cx); self.sync_generation += 1; self.reset_channel_tabs(cx); self.reset_recap(cx); self.reload_pending(cx); self.notice = None; self.scheduled_failure = None; self.app.update(cx, |state, cx| state.refresh_scheduled(cx)); self.rebuild(true, cx); self.start_fetch(cx); self.mark_read(ReadTrigger::Open, cx); self.refresh_pin_previews(cx); self.pinned_posts_expanded = false; if let Some(conversation_id) = self.pin_conversation_id() { self.app .update(cx, |state, cx| state.refresh_pins(&conversation_id, cx)); } let conversation_id = self .current .as_ref() .map(|current| current.selection.conversation_id().to_owned()) .unwrap_or_default(); self.composer.update(cx, |composer, cx| { composer.set_conversation(&conversation_id, window, cx); }); self.sync_reply_composer(window, cx); if self.in_feed() { window.focus(&self.focus_handle, cx); } else if !self.draft_active { self.composer .update(cx, |composer, cx| composer.focus(window, cx)); } self.hovered_message = None; self.pointer_on = PointerOn::default(); self.apply_pending_jump(cx); } fn enter_draft(&mut self, window: &mut Window, cx: &mut Context) { if !self.draft_active { self.stop_typing(cx); self.draft_active = true; self.current = None; self.clear_pending(); self.notice = None; self.draft_created = None; self.draft_error = None; self.toolbar_hovered = None; self.toolbar_pinned = None; self.toolbar_suppressed = None; self.hovered_message = None; self.pointer_on = PointerOn::default(); self.sync_generation += 1; self.draft.update(cx, |draft, cx| draft.reset(window, cx)); self.composer .update(cx, |composer, cx| composer.set_conversation("", window, cx)); self.on_draft_changed(window, cx); self.rebuild(true, cx); } let people = self .app .update(cx, |state, _| std::mem::take(&mut state.new_chat_people)); if !people.is_empty() { let chips = people .into_iter() .filter_map(|person| { Some(Pick { user_id: person.user_id?, name: person.display_name, mail: None, organization: None, }) }) .collect(); self.draft .update(cx, |draft, cx| draft.set_chips(chips, cx)); } self.draft .update(cx, |draft, cx| draft.focus_query(window, cx)); cx.notify(); } fn leave_draft(&mut self, window: &mut Window, cx: &mut Context) { self.draft_active = false; self.draft_created = None; self.draft_error = None; self.clear_pending(); self.draft.update(cx, |draft, cx| draft.reset(window, cx)); } fn on_draft_event( &mut self, _: &Entity, event: &NewChatEvent, window: &mut Window, cx: &mut Context, ) { match event { NewChatEvent::Changed => self.on_draft_changed(window, cx), NewChatEvent::FocusComposer => self .composer .update(cx, |composer, cx| composer.focus(window, cx)), NewChatEvent::Close => self.app.update(cx, |state, cx| state.close_new_chat(cx)), } } fn draft_target_chat(&self, cx: &App) -> Option { let chips = self.draft.read(cx).chips(); let [chip] = chips else { return None; }; let state = self.app.read(cx); existing_one_on_one( &state.sidebar.chats, state.directory.me.as_ref(), &chip.user_id, ) .map(|chat| chat.id.clone()) } fn on_draft_changed(&mut self, window: &mut Window, cx: &mut Context) { if !self.draft_active { return; } let target = self.draft_target_chat(cx); if target != self.conversation_id() { match target { Some(chat_id) => { self.composer.update(cx, |composer, _| { composer.carry_images_into(chat_id.clone()) }); self.open(Selection::Chat(chat_id), window, cx) } None => { self.composer.update(cx, |composer, cx| { composer.carry_images_into(String::new()); composer.set_conversation("", window, cx); }); self.current = None; self.sync_generation += 1; self.rebuild(true, cx); } } } let placeholder = { let draft = self.draft.read(cx); composer_placeholder(draft.chips(), &draft.group_name(cx)) }; self.composer.update(cx, |composer, cx| { composer.set_placeholder(&placeholder, window, cx) }); cx.notify(); } fn remeasure_images(&mut self, keys: &[String], cx: &mut Context) { let indices: Vec = self .rows .borrow() .iter() .enumerate() .filter(|(_, row)| { row.messages().any(|message| { message.images.iter().any(|image| keys.contains(&image.url)) || message .link_preview .as_ref() .and_then(LinkPreview::image) .is_some_and(|image| keys.contains(&image.url)) }) }) .map(|(index, _)| index) .collect(); self.scroller.update(cx, |scroller, cx| { for index in indices { scroller.remeasure_items(index..index + 1, cx); } }); cx.notify(); } fn refresh_cards(&mut self, conversation_id: &str, cx: &mut Context) { let is_current = self .current .as_ref() .is_some_and(|current| current.selection.conversation_id() == conversation_id); if !is_current { return; } self.rebuild(false, cx); let indices: Vec = self .rows .borrow() .iter() .enumerate() .filter(|(_, row)| { row.messages() .any(|message| !message.adaptive_cards.is_empty()) }) .map(|(index, _)| index) .collect(); self.scroller.update(cx, |scroller, cx| { for index in indices { scroller.remeasure_items(index..index + 1, cx); } }); cx.notify(); } fn apply_pending_jump(&mut self, cx: &mut Context) { let Some(conversation_id) = self .current .as_ref() .map(|current| current.selection.conversation_id().to_owned()) else { return; }; let jump = self .app .update(cx, |state, _| match state.pending_jump.take() { Some((target, message_id)) if target == conversation_id => Some(message_id), other => { state.pending_jump = other; None } }); if let Some(message_id) = jump { self.jump_to_message(&conversation_id, &message_id, cx); } } fn jump_to_message(&mut self, conversation_id: &str, message_id: &str, cx: &mut Context) { self.jump_to_post(conversation_id, message_id, true, cx); } fn jump_to_post( &mut self, conversation_id: &str, message_id: &str, refresh_replies: bool, cx: &mut Context, ) { let store = self.app.read(cx).store.clone(); let record = store .messages_by_id(conversation_id, &[message_id.to_owned()]) .ok() .and_then(|mut found| found.remove(message_id)); if self.chat_id().as_deref() == Some(conversation_id) { let created_at = record.as_ref().map(|record| record.created_at); match self.jump_plan_for(conversation_id, created_at, cx) { JumpPlan::LoadWindow => { self.open_detached(conversation_id.to_owned(), message_id.to_owned(), cx); return; } plan => { if let Some(current) = self.current.as_mut() { current.window_request = None; if plan == JumpPlan::LeaveWindow { current.detached = None; } } } } } let Some(record) = record else { self.open_unloaded_post(message_id, cx); return; }; let messages_from_target = store .messages(conversation_id, None, JUMP_SCAN_LIMIT) .ok() .and_then(|all| { all.iter() .position(|candidate| candidate.message_id == message_id) .map(|position| all.len() - position) }) .unwrap_or_default(); let row_key = record .reply_to_id .clone() .unwrap_or_else(|| message_id.to_owned()); let Some(current) = self.current.as_mut() else { return; }; current.loaded_limit = current .loaded_limit .max(messages_from_target + JUMP_CONTEXT_MESSAGES); current.first_unread = None; let in_channel = matches!(current.selection, Selection::Channel(_)); if in_channel { self.pane = ChannelPane::Posts; self.enter_feed_mode(); self.stop_typing(cx); self.enter_thread_mode(row_key.clone(), cx); } self.reload_pending(cx); self.rebuild(true, cx); if in_channel { if refresh_replies { self.refresh_thread(row_key.clone(), cx); } let shown_alone = self.rows.borrow().iter().any(|row| row.key() == message_id); if shown_alone { self.reveal_row(message_id.to_owned(), message_id.to_owned(), cx); return; } } self.reveal_row(row_key, message_id.to_owned(), cx); } fn open_unloaded_post(&mut self, message_id: &str, cx: &mut Context) { let state = self.app.read(cx); let (Some(engine), Some(current)) = (state.engine.clone(), self.current.as_ref()) else { return; }; if !matches!(current.selection, Selection::Channel(_)) || state.mode.demo || self.fetched_jump.as_deref() == Some(message_id) { return; } self.fetched_jump = Some(message_id.to_owned()); let conversation_id = current.selection.conversation_id().to_owned(); let (task_conversation_id, task_message_id) = (conversation_id.clone(), message_id.to_owned()); let receiver = runtime::spawn(async move { engine .open_post(&task_conversation_id, &task_message_id) .await }); let message_id = message_id.to_owned(); self.show_loading_post(message_id.clone(), cx); cx.spawn(async move |this, cx| { let result = receiver.await; this.update(cx, |this, cx| { this.finish_loading_post(&conversation_id, &message_id, result, cx) }) .ok(); }) .detach(); } fn show_loading_post(&mut self, message_id: String, cx: &mut Context) { self.pane = ChannelPane::Posts; self.enter_feed_mode(); self.stop_typing(cx); self.enter_thread_mode(message_id.clone(), cx); self.loading_post = Some(message_id); self.rebuild(true, cx); } fn finish_loading_post( &mut self, conversation_id: &str, message_id: &str, result: Result< teams_core::Result>, tokio::sync::oneshot::error::RecvError, >, cx: &mut Context, ) { if self.loading_post.as_deref() != Some(message_id) { return; } self.loading_post = None; if self.conversation_id().as_deref() != Some(conversation_id) { return; } let still_waiting = self .current .as_ref() .is_some_and(|current| current.mode == ViewMode::Thread(message_id.to_owned())); match result { Ok(Ok(Some(post))) if still_waiting => { self.jump_to_post(conversation_id, message_id, !post.replies_loaded, cx) } Ok(Ok(Some(_))) => self.rebuild(true, cx), failure => { if let Ok(Err(error)) = &failure { self.notice = Some(format!("Could not load the post: {}", short_error(error))); } if still_waiting { self.back_to_threads(cx); } else { cx.notify(); } } } } fn reveal_row(&mut self, row_key: String, message_key: String, cx: &mut Context) { let index = self .rows .borrow() .iter() .position(|row| row.key() == row_key); if let Some(index) = index { self.scroller .update(cx, |scroller, cx| scroller.scroll_to_item(index, cx)); self.highlight(message_key, cx); } } fn highlight(&mut self, key: String, cx: &mut Context) { self.highlighted_message = Some(key.clone()); cx.notify(); cx.spawn(async move |this, cx| { cx.background_executor().timer(JUMP_HIGHLIGHT_PERIOD).await; this.update(cx, |this, cx| { if this.highlighted_message.as_deref() == Some(key.as_str()) { this.highlighted_message = None; cx.notify(); } }) .ok(); }) .detach(); } pub fn set_composer_text(&mut self, text: &str, window: &mut Window, cx: &mut Context) { self.composer .update(cx, |composer, cx| composer.set_text(text, window, cx)); self.composer .update(cx, |composer, cx| composer.focus(window, cx)); } pub fn focus_composer(&mut self, window: &mut Window, cx: &mut Context) { self.composer .update(cx, |composer, cx| composer.focus(window, cx)); } pub fn reply_to_latest_from_others(&mut self, window: &mut Window, cx: &mut Context) { let key = self .rows .borrow() .iter() .rev() .flat_map(Row::messages) .find(|message| !message.own) .map(|message| message.key.clone()); if let Some(key) = key { self.begin_reply(&key, window, cx); } } pub fn reply_to_hovered(&mut self, window: &mut Window, cx: &mut Context) { if let Some(message_id) = self.hovered_message.clone() { self.begin_reply(&message_id, window, cx); } } fn reply_target(&self, message_id: &str, cx: &App) -> Option<(MessageRecord, ReplyPreview)> { let conversation_id = self.conversation_id()?; let record = self .app .read(cx) .store .messages_by_id(&conversation_id, &[message_id.to_owned()]) .ok() .and_then(|mut found| found.remove(message_id)) .filter(|record| !record.deleted)?; let preview = ReplyPreview { message_id: record.message_id.clone(), author: record .sender_name .clone() .unwrap_or_else(|| "Unknown".to_owned()), excerpt: reply_excerpt(&record), }; Some((record, preview)) } fn begin_reply(&mut self, message_id: &str, window: &mut Window, cx: &mut Context) { let Some((record, preview)) = self.reply_target(message_id, cx) else { return; }; if self.in_feed() { let root_id = record .reply_to_id .clone() .unwrap_or_else(|| record.message_id.clone()); self.open_reply_editor(root_id, Some(preview), window, cx); return; } self.composer.update(cx, |composer, cx| { if composer.is_editing() { composer.cancel_edit(window, cx); } composer.set_reply(Some(preview), cx); composer.focus(window, cx); }); } fn channel_read_until(&self, selection: &Selection, cx: &App) -> Option> { let Selection::Channel(channel_id) = selection else { return None; }; let state = self.app.read(cx); if state.mode.demo { return crate::demo::channel_read_until(channel_id); } state.engine.as_ref()?.channel_read_until(channel_id) } fn first_unread_id(&self, selection: &Selection, cx: &App) -> Option { let Selection::Chat(chat_id) = selection else { return None; }; let state = self.app.read(cx); if state.mode.demo { return crate::demo::first_unread(chat_id); } state.engine.as_ref()?.first_unread_message_id(chat_id) } fn row_context(&self, cx: &App) -> RowContext { let now = Local::now(); let app = self.app.read(cx); let names = local_names(app); let card_overrides = self .current .as_ref() .map(|current| app.cards.overrides_for(current.selection.conversation_id())) .unwrap_or_default(); let translation = self .current .as_ref() .map(|current| { app.translation .context_for(current.selection.conversation_id()) }) .unwrap_or_default(); RowContext { offset: app_base::format::Zone::Local, today: now.date_naive(), my_user_id: app.store.meta(META_USER_ID).ok().flatten(), names, pending_reactions: self.pending_reactions.clone(), card_overrides, translation, skin_tone: teams_core::skin_tone(&app.store), meeting: self.meeting_info(app), } } fn unknown_reactor_ids(&self) -> Vec { self.rows .borrow() .iter() .flat_map(Row::messages) .flat_map(|message| message.reactions.iter()) .flat_map(|chip| chip.reactors.iter()) .filter(|reactor| reactor.name == UNKNOWN_REACTOR) .filter_map(|reactor| reactor.user_id.clone()) .collect() } fn refresh_reactor_names(&mut self, cx: &mut Context) { if self.current.is_none() { return; } let unknown = self.unknown_reactor_ids(); if unknown.is_empty() { return; } let names = resolve_names(self.app.read(cx), &unknown); if !names.is_empty() { self.rebuild(false, cx); } } fn drop_stale_reaction_details(&mut self) { let Some(details) = self.reaction_details.as_ref() else { return; }; let present = self .rows .borrow() .iter() .flat_map(Row::messages) .any(|message| { message.key == details.message_key && message .reactions .iter() .any(|chip| chip.glyph() == details.anchor_glyph) }); if !present { self.reaction_details = None; } } fn open_reaction_details(&mut self, message_key: &str, glyph: &str, cx: &mut Context) { let multiple_kinds = self .rows .borrow() .iter() .flat_map(Row::messages) .any(|message| message.key == message_key && message.reactions.len() > 1); self.reaction_details = Some(ReactionDetails { message_key: message_key.to_owned(), anchor_glyph: glyph.to_owned(), tab: multiple_kinds.then(|| glyph.to_owned()), }); cx.notify(); } fn select_reaction_tab(&mut self, tab: Option, cx: &mut Context) { if let Some(details) = self.reaction_details.as_mut() { details.tab = tab; cx.notify(); } } fn close_reaction_details(&mut self, cx: &mut Context) { if self.reaction_details.take().is_some() { cx.notify(); } } fn reaction_controls(&self, key: &str, view: WeakEntity) -> ReactionControls { let open = { let (view, key) = (view.clone(), key.to_owned()); Rc::new(move |glyph: &str, cx: &mut App| { view.update(cx, |this, cx| this.open_reaction_details(&key, glyph, cx)) .ok(); }) }; let select_tab = { let view = view.clone(); Rc::new(move |tab: Option, cx: &mut App| { view.update(cx, |this, cx| this.select_reaction_tab(tab, cx)) .ok(); }) }; let close = Rc::new(move |cx: &mut App| { view.update(cx, |this, cx| this.close_reaction_details(cx)) .ok(); }); let popover = self .reaction_details .as_ref() .filter(|details| details.message_key == key) .map(|details| ReactionPopover { anchor_glyph: details.anchor_glyph.clone(), tab: details.tab.clone(), }); ReactionControls { open, select_tab, close, popover, } } fn start_info(&self, cx: &App) -> Option { let current = self.current.as_ref()?; let app = self.app.read(cx); let (user_id, member_name, notes) = match ¤t.selection { Selection::Chat(chat_id) if app.sidebar.chats.iter().any(|chat| { &chat.id == chat_id && chat.kind.eq_ignore_ascii_case("meeting") }) => { return None; } Selection::Chat(chat_id) => { let member = app .sidebar .chats .iter() .find(|chat| &chat.id == chat_id) .filter(|chat| is_one_on_one(chat)) .and_then(|chat| others(chat, app.directory.me.as_ref()).into_iter().next()); let (user_id, name) = member.unzip(); (user_id.flatten(), name, is_notes_chat(chat_id)) } Selection::Channel(_) => (None, None, false), }; Some(StartInfo { title: current.title.clone(), user_id, avatar_name: member_name .filter(|name| !name.is_empty()) .unwrap_or_else(|| current.title.clone()), notes, }) } fn notes_space(&self) -> Option { match self.rows.borrow().as_slice() { [Row::Start(start)] if start.notes => Some(start.clone()), _ => None, } } fn watch_feed_scroll(&mut self, cx: &mut Context) { let scroller_id = self.scroller.entity_id(); if self .scroller_watch .as_ref() .is_some_and(|(watched, _)| *watched == scroller_id) { return; } let subscription = cx.observe(&self.scroller, |this, _, cx| { if this.in_feed() { cx.notify(); } }); self.scroller_watch = Some((scroller_id, subscription)); } fn rebuild(&mut self, reset: bool, cx: &mut Context) { let started = std::time::Instant::now(); self.rebuild_generation += 1; match self.rebuild_plan(reset, cx) { Some(plan) => { let loaded = load_records(&self.app.read(cx).store, &plan); let context = self.complete_context(&loaded.records, cx); let built = build_rows(&plan, &loaded, &context); self.finish_rebuild(plan, loaded, context, built, reset, cx); } None => self.rebuild_without_conversation(cx), } app_base::diagnostics::record_if_slow("conversation rebuild", started.elapsed()); } fn rebuild_in_background(&mut self, cx: &mut Context) { let Some(plan) = self.rebuild_plan(false, cx) else { return self.rebuild(false, cx); }; self.rebuild_generation += 1; let generation = self.rebuild_generation; let store = self.app.read(cx).store.clone(); let date_style = app_base::format::current_date_style(); cx.spawn(async move |this, cx| { let (plan, loaded) = cx .background_spawn(async move { let loaded = load_records(&store, &plan); (plan, loaded) }) .await; let Ok(Some(context)) = this.update(cx, |view, cx| { view.rebuild_still_current(generation, &plan) .then(|| view.complete_context(&loaded.records, cx)) }) else { return; }; let (plan, loaded, context, built) = cx .background_spawn(async move { // The regional format is per thread: without it the times fall back to 24 h. app_base::format::set_date_style(date_style); let built = build_rows(&plan, &loaded, &context); (plan, loaded, context, built) }) .await; this.update(cx, |view, cx| { if view.rebuild_still_current(generation, &plan) { let started = std::time::Instant::now(); view.finish_rebuild(plan, loaded, context, built, false, cx); app_base::diagnostics::record_if_slow( "conversation rebuild apply", started.elapsed(), ); } }) .ok(); }) .detach(); } fn rebuild_still_current(&self, generation: u64, plan: &RebuildPlan) -> bool { generation == self.rebuild_generation && self.current.as_ref().is_some_and(|current| { current.selection.conversation_id() == plan.conversation_id && current.mode == plan.mode }) } fn rebuild_without_conversation(&mut self, cx: &mut Context) { let mut rows: Vec = self .pending .iter() .cloned() .map(|row| Row::Message(Box::new(row))) .collect(); assign_series(&mut rows); self.apply_rows(rows, true, cx); } fn rebuild_plan(&self, reset: bool, cx: &App) -> Option { let current = self.current.as_ref()?; let limit = if reset { current.loaded_limit } else { current .loaded_limit .max(current.loaded_count + GROWTH_HEADROOM) }; let thread_root = match ¤t.mode { ViewMode::Thread(root_id) => Some(root_id.clone()), ViewMode::Flat | ViewMode::ThreadList => None, }; Some(RebuildPlan { conversation_id: current.selection.conversation_id().to_owned(), is_chat: matches!(current.selection, Selection::Chat(_)), mode: current.mode.clone(), limit, loading_post: thread_root.is_some() && thread_root == self.loading_post, thread_root, window: current.detached.as_ref().map(|detached| { ( detached.oldest, detached.newest, detached.older_cursor.is_some(), detached.newer_cursor.is_some(), ) }), syncing_messages: current.sync.messages, older_blocked: current.older_blocked, can_load_older: self.app.read(cx).engine.is_some(), start: self.start_info(cx), }) } fn complete_context(&self, records: &[MessageRecord], cx: &App) -> RowContext { let mut context = self.row_context(cx); let unnamed_ids: Vec = records .iter() .flat_map(teams_core::reactions) .filter(|reaction| reaction.user_name.is_none()) .filter_map(|reaction| reaction.user_id) .chain(forward_sender_ids(records)) .filter(|user_id| !context.names.contains_key(user_id)) .collect(); for (user_id, name) in resolve_names(self.app.read(cx), &unnamed_ids) { context.names.entry(user_id).or_insert(name); } for record in records { if let (Some(user_id), Some(name)) = (&record.sender_id, &record.sender_name) { context .names .entry(user_id.clone()) .or_insert_with(|| name.clone()); } } context } fn finish_rebuild( &mut self, plan: RebuildPlan, loaded: LoadedRecords, context: RowContext, built: BuiltRows, reset: bool, cx: &mut Context, ) { let records = loaded.records; let current = self.current.as_mut().expect("checked by the plan"); let first_unread = current.first_unread.clone(); let posts_new_after = current.posts_new_after; current.loaded_limit = plan.limit; if plan.thread_root.is_none() { current.loaded_count = records.len(); } current.has_older = built.has_older; let in_feed = current.mode == ViewMode::ThreadList; let appear_scope = format!("{}/{:?}", plan.conversation_id, current.mode); let appear_live = !built.placeholders && !in_feed && plan.window.is_none() && !current.sync.messages; let mut rows = built.rows; let local: Vec = if plan.window.is_some() { Vec::new() } else { self.pending .iter() .cloned() .chain(self.scheduled_rows(context.my_user_id.as_deref(), cx)) .collect() }; if in_feed { place_local_rows(&mut rows, local); } else { rows.extend(local.into_iter().map(|row| Row::Message(Box::new(row)))); } let (mut receipts, receipt_labels) = self.receipts(&records, cx); if self.track_receipt_fades(&mut receipts) { self.schedule_fade_end(cx); } for row in rows.iter_mut() { if let Row::Message(message) = row && message.own { message.receipt = receipts.get(&message.key).copied().unwrap_or_default(); message.receipt_label = receipt_labels.get(&message.key).cloned(); if let Some((_, previews)) = self .sent_previews .iter() .find(|(key, _)| key == &message.key) { message.sent_previews = previews.clone(); } } } if let Some(read_until) = posts_new_after.filter(|_| in_feed) { for row in rows.iter_mut() { if let Row::Post(post) = row { post.mark_new_after(read_until); } } } if let Some(unread_id) = &first_unread { for row in rows.iter_mut() { if let Row::Message(message) = row && &message.key == unread_id { message.new_marker = true; } } } assign_series(&mut rows); self.track_appearing(&rows, &appear_scope, appear_live, reset); self.apply_rows(rows, reset, cx); if self.is_detached() { self.scroller .update(cx, |scroller, _| scroller.stop_following()); } } fn apply_rows(&mut self, mut new_rows: Vec, reset: bool, cx: &mut Context) { for row in &mut new_rows { if let Row::Message(message) = row && message.delivery == Delivery::Delivered && self.saving_edits.contains(&message.key) { message.delivery = Delivery::Sending; } } let old_rows = std::mem::replace(&mut *self.rows.borrow_mut(), new_rows); self.drop_stale_reaction_details(); let new_len = self.rows.borrow().len(); let in_feed = self.in_feed(); let older_anchor = self.older_anchor.take().and_then(|key| { let top_was_loader = matches!(old_rows.first(), Some(Row::LoadOlder)); let index = self.rows.borrow().iter().position(|row| row.key() == key)?; (top_was_loader && !in_feed).then_some(index) }); if reset { let marker_index = self .rows .borrow() .iter() .position(|row| matches!(row, Row::Message(message) if message.new_marker)); self.feed_at_top = true; self.scroller.update(cx, |scroller, cx| { scroller.reset(new_len, cx); if in_feed { scroller.scroll_to_item(0, cx); return; } match marker_index { Some(index) if !scroller.scroll_to_item(index, cx) => { scroller.scroll_to_end(cx) } Some(_) => {} None => scroller.scroll_to_end(cx), } }); cx.notify(); return; } let (splice, changed) = { let new_rows = self.rows.borrow(); let old_keys: Vec = old_rows.iter().map(|row| row.key().to_owned()).collect(); let new_keys: Vec = new_rows.iter().map(|row| row.key().to_owned()).collect(); ( diff_keys(&old_keys, &new_keys), changed_indices(&old_rows, &new_rows), ) }; let top_changed = splice .as_ref() .is_some_and(|splice| splice.range.start == 0); let keep_top = in_feed && (old_rows.is_empty() || (self.feed_at_top && top_changed)); self.scroller.update(cx, |scroller, cx| { if let Some(splice) = splice && !scroller.splice(splice.range, splice.count, cx) { scroller.reset(new_len, cx); } if keep_top { scroller.scroll_to_item(0, cx); } else if let Some(index) = older_anchor { scroller.scroll_to_item(index, cx); } for index in changed { scroller.remeasure_items(index..index + 1, cx); } }); cx.notify(); } fn start_fetch(&mut self, cx: &mut Context) { let state = self.app.read(cx); let (engine, demo_sync) = (state.engine.clone(), state.mode.demo_sync); if engine.is_none() && demo_sync.is_none() { return; } let Some(current) = self.current.as_mut() else { return; }; if current.fetched { return; } current.fetched = true; let is_chat = matches!(current.selection, Selection::Chat(_)); let newest_cached = self .rows .borrow() .iter() .flat_map(Row::messages) .filter(|message| !message.key.starts_with(PENDING_KEY_PREFIX)) .map(|message| message.created_at) .max(); let current = self.current.as_mut().expect("checked above"); if current.sync.failed { self.notice = None; } current.sync = SyncProgress { messages: true, receipts: is_chat, empty_cache: newest_cached.is_none(), newest_cached, started_at: Utc::now(), ..SyncProgress::default() }; self.sync_generation += 1; let generation = self.sync_generation; let conversation_id = current.selection.conversation_id().to_owned(); match (engine, demo_sync) { (Some(engine), _) => { let receiver = runtime::spawn(async move { engine.fetch_newer(&conversation_id).await }); cx.spawn(async move |this, cx| { let result = receiver.await; this.update(cx, |this, cx| this.finish_fetch(generation, result, cx)) .ok(); }) .detach(); } (None, Some(delay)) => self.simulate_sync(generation, delay, cx), (None, None) => {} } self.schedule_progress(generation, cx); self.rebuild(false, cx); self.mark_read(ReadTrigger::Incoming, cx); self.refresh_receipts(generation, cx); } fn simulate_sync(&mut self, generation: u64, delay: Duration, cx: &mut Context) { cx.spawn(async move |this, cx| { cx.background_executor().timer(delay).await; this.update(cx, |this, cx| { if let Some(sync) = this.sync_of(generation) { sync.receipts = false; } this.finish_fetch(generation, Ok(Ok(teams_core::Delta::default())), cx) }) .ok(); }) .detach(); } fn sync_of(&mut self, generation: u64) -> Option<&mut SyncProgress> { if generation != self.sync_generation { return None; } self.current.as_mut().map(|current| &mut current.sync) } fn schedule_progress(&mut self, generation: u64, cx: &mut Context) { cx.spawn(async move |this, cx| { let stages = [ (PROGRESS_DELAY, Duration::ZERO), (SLOW_AFTER, PROGRESS_DELAY), ]; for (stage, (at, previous)) in stages.into_iter().enumerate() { cx.background_executor().timer(at - previous).await; let running = this .update(cx, |this, cx| this.advance_progress(generation, stage, cx)) .unwrap_or(false); if !running { return; } } }) .detach(); } fn advance_progress(&mut self, generation: u64, stage: usize, cx: &mut Context) -> bool { let Some(sync) = self.sync_of(generation) else { return false; }; if !sync.running() || !sync.empty_cache { return false; } match stage { 0 => sync.shown_at = Some(Instant::now()), _ => sync.slow = true, } cx.notify(); true } fn finish_fetch( &mut self, generation: u64, result: Result< teams_core::Result, tokio::sync::oneshot::error::RecvError, >, cx: &mut Context, ) { let Some(sync) = self.sync_of(generation) else { return; }; sync.messages = false; let (newest_cached, started_at) = (sync.newest_cached, sync.started_at); match result { Ok(Ok(_)) => { if let Some(current) = self.current.as_mut() { current.quiet_retries = 0; } self.mark_fetched_new(newest_cached, started_at, cx) } Ok(Err(error)) if Self::denies_access(&error) => self.fail_access(generation), Ok(Err(error)) => self.fail_sync(generation, short_error(&error), cx), Err(error) => self.fail_sync(generation, short_error(&error), cx), } self.rebuild(false, cx); self.settle_progress(generation, cx); } fn fail_sync(&mut self, generation: u64, error: String, cx: &mut Context) { let quiet_retry = self.current.as_mut().and_then(|current| { let delay = QUIET_RETRY_DELAYS.get(current.quiet_retries).copied()?; current.quiet_retries += 1; Some(delay) }); if let Some(delay) = quiet_retry { cx.spawn(async move |this, cx| { cx.background_executor().timer(delay).await; this.update(cx, |this, cx| { if this.sync_generation == generation { this.retry_fetch(cx); } }) .ok(); }) .detach(); return; } if let Some(sync) = self.sync_of(generation) { sync.failed = true; sync.receipts = false; } self.notice = Some(format!("Could not refresh: {error}")); } fn denies_access(error: &teams_core::Error) -> bool { matches!(error, teams_core::Error::Graph(graph::Error::NotAMember)) } fn fail_access(&mut self, generation: u64) { if let Some(sync) = self.sync_of(generation) { sync.failed = true; sync.receipts = false; } self.notice = Some("No access to this chat".to_owned()); } fn mark_fetched_new( &mut self, newest_cached: Option>, started_at: DateTime, cx: &mut Context, ) { let Some(newest_cached) = newest_cached else { return; }; let Some(my_user_id) = self.row_context(cx).my_user_id else { return; }; let store = self.app.read(cx).store.clone(); let Some(current) = self.current.as_mut() else { return; }; if current.first_unread.is_some() || current.mode != ViewMode::Flat { return; } let limit = current .loaded_limit .max(current.loaded_count + GROWTH_HEADROOM); current.first_unread = store .messages(current.selection.conversation_id(), None, limit) .unwrap_or_default() .into_iter() .find(|record| { missed_before_fetch(record.created_at, newest_cached, started_at) && record.sender_id.as_ref() != Some(&my_user_id) }) .map(|record| record.message_id); } fn settle_progress(&mut self, generation: u64, cx: &mut Context) { let Some(sync) = self.sync_of(generation) else { return; }; if sync.running() { return; } let remaining = sync .shown_at .map(|shown_at| PROGRESS_MIN_VISIBLE.saturating_sub(shown_at.elapsed())) .unwrap_or_default(); if remaining.is_zero() { sync.shown_at = None; sync.slow = false; cx.notify(); return; } cx.spawn(async move |this, cx| { cx.background_executor().timer(remaining).await; this.update(cx, |this, cx| { if let Some(sync) = this.sync_of(generation) { sync.shown_at = None; sync.slow = false; cx.notify(); } }) .ok(); }) .detach(); } fn retry_fetch(&mut self, cx: &mut Context) { if let Some(current) = self.current.as_mut() { current.fetched = false; } self.start_fetch(cx); } fn receipts( &self, records: &[MessageRecord], cx: &App, ) -> (HashMap, HashMap) { let settings = self.app.read(cx).account_chat_settings(); let (mut receipts, mut labels) = self.raw_receipts(records, cx); for receipt in receipts.values_mut() { *receipt = shown_receipt(&settings, *receipt); } labels.retain(|key, _| { receipts .get(key) .is_some_and(|receipt| *receipt != Receipt::Hidden) }); (receipts, labels) } fn raw_receipts( &self, records: &[MessageRecord], cx: &App, ) -> (HashMap, HashMap) { let state = self.app.read(cx); if state.mode.demo { let read_ids = crate::demo::read_message_ids(records); let receipts: HashMap = records .iter() .map(|record| { let receipt = if read_ids.contains(&record.message_id) { Receipt::Read } else { Receipt::Sent }; (record.message_id.clone(), receipt) }) .collect(); let labels = receipts .iter() .map(|(key, receipt)| { let label = if *receipt == Receipt::Read { "Seen" } else { "Sent" }; (key.clone(), label.to_owned()) }) .collect(); return (receipts, labels); } let Some(engine) = state.engine.as_ref() else { return (HashMap::new(), HashMap::new()); }; let mut receipts = HashMap::new(); let mut labels = HashMap::new(); for record in records { let receipt_state = engine.receipt_state_for(record); if let Some(label) = crate::rows::receipt_label(&receipt_state) { labels.insert(record.message_id.clone(), label); } let receipt = match receipt_state { teams_core::ReceiptState::Read { .. } => Receipt::Read, teams_core::ReceiptState::Sent => Receipt::Sent, teams_core::ReceiptState::Unknown => Receipt::Hidden, }; receipts.insert(record.message_id.clone(), receipt); } (receipts, labels) } fn track_receipt_fades(&mut self, receipts: &mut HashMap) -> bool { let Some(current) = self.current.as_ref() else { return false; }; let settled = !current.sync.receipts; let conversation_id = current.selection.conversation_id().to_owned(); self.receipt_fade .apply(&conversation_id, settled, receipts, Instant::now()) } fn track_appearing(&mut self, rows: &[Row], scope: &str, live: bool, reset: bool) { let sending: HashSet<&str> = self.pending.iter().map(|row| row.key.as_str()).collect(); let candidates: Vec = rows .iter() .filter_map(|row| match row { Row::Message(message) => Some(appear_tracker::Candidate { key: &message.key, own: message.own, origin: if sending.contains(message.key.as_str()) { appear_tracker::Origin::Sending } else if message.key.starts_with(SCHEDULED_KEY_PREFIX) { appear_tracker::Origin::Scheduled } else { appear_tracker::Origin::Server }, }), _ => None, }) .collect(); self.appear_tracker .apply(scope, live, reset, &candidates, Instant::now()); } fn schedule_fade_end(&mut self, cx: &mut Context) { cx.spawn(async move |this, cx| { cx.background_executor() .timer(receipt_fade::RECEIPT_FADE) .await; this.update(cx, |this, cx| this.rebuild(false, cx)).ok(); }) .detach(); } fn refresh_receipts(&mut self, generation: u64, cx: &mut Context) { let state = self.app.read(cx); let (Some(engine), Some(Selection::Chat(chat_id))) = ( state.engine.clone(), self.current.as_ref().map(|c| c.selection.clone()), ) else { return; }; let receiver = runtime::spawn(async move { engine.refresh_receipts(&chat_id).await }); cx.spawn(async move |this, cx| { receiver.await.ok(); this.update(cx, |this, cx| { let Some(sync) = this.sync_of(generation) else { return; }; sync.receipts = false; this.rebuild(false, cx); this.settle_progress(generation, cx); }) .ok(); }) .detach(); } fn mark_read(&mut self, trigger: ReadTrigger, cx: &mut Context) { if self.draft_active { return; } let state = self.app.read(cx); let Some(selection) = self.current.as_ref().map(|c| c.selection.clone()) else { return; }; if (state.engine.is_none() && !state.mode.demo) || state.mode.read_only { return; } let unread = match &selection { Selection::Chat(chat_id) => { state .sidebar .chats .iter() .any(|chat| &chat.id == chat_id && chat.unread) && !state.keeps_unread(chat_id) } Selection::Channel(channel_id) => channel_unread(&state.sidebar, channel_id), }; let Some(plan) = plan_read(self.window_active, unread, trigger) else { return; }; self.app.update(cx, |state, cx| match &selection { Selection::Chat(chat_id) => { state.ack_urgent_messages(chat_id, cx); state.mark_chat_read(chat_id, cx) } Selection::Channel(channel_id) => state.mark_channel_read(channel_id, cx), }); if plan.clear_divider && let Some(current) = self.current.as_mut() && current.first_unread.take().is_some() { self.rebuild(false, cx); } } fn request_older(&mut self, cx: &mut Context) { if self.is_detached() { return self.request_window_page(WindowDirection::Backward, cx); } let Some(engine) = self.app.read(cx).engine.clone() else { return; }; let Some(current) = self.current.as_mut() else { return; }; if current.loading_older || current.older_blocked || !current.has_older { return; } current.loading_older = true; let conversation_id = current.selection.conversation_id().to_owned(); let task_id = conversation_id.clone(); let receiver = runtime::spawn(async move { engine.load_older(&task_id).await }); cx.spawn(async move |this, cx| { let result = receiver.await; this.update(cx, |this, cx| { this.finish_older(&conversation_id, result, cx) }) .ok(); }) .detach(); } fn finish_older( &mut self, conversation_id: &str, result: Result< teams_core::Result>, tokio::sync::oneshot::error::RecvError, >, cx: &mut Context, ) { let Some(current) = self.current.as_mut() else { return; }; if current.selection.conversation_id() != conversation_id { return; } current.loading_older = false; match result { Ok(Ok(records)) if !records.is_empty() => { app_base::diagnostics::record(&format!( "chat: older page, {} messages", records.len() )); current.loaded_limit = current.loaded_count + records.len(); self.older_anchor = self .rows .borrow() .iter() .find(|row| matches!(row, Row::Message(_) | Row::Post(_))) .map(|row| row.key().to_owned()); } Ok(Ok(_)) => { app_base::diagnostics::record("chat: no older messages"); current.older_blocked = true; } Ok(Err(error)) => { app_base::diagnostics::record(&format!( "chat: older page failed: {}", short_error(&error) )); current.older_blocked = true; self.notice = Some(format!( "Could not load older messages: {}", short_error(&error) )); } Err(_) => current.older_blocked = true, } self.rebuild(false, cx); } fn clear_pending(&mut self) { self.pending.clear(); self.pending_outgoing.clear(); } fn outbox_route(&self, reply_root: Option) -> (OutboxTarget, Option) { if let Some(root_id) = reply_root { return (OutboxTarget::Thread, Some(root_id)); } match self.current.as_ref().map(|current| ¤t.mode) { Some(ViewMode::Thread(root_id)) => (OutboxTarget::Thread, Some(root_id.clone())), Some(ViewMode::ThreadList) => (OutboxTarget::Post, None), _ => (OutboxTarget::Flat, None), } } fn reload_pending(&mut self, cx: &App) { self.clear_pending(); let state = self.app.read(cx); if state.mode.demo || state.mode.read_only { return; } let Some(current) = self.current.as_ref() else { return; }; let conversation_id = current.selection.conversation_id().to_owned(); let Ok(records) = state.store.outbox_for_conversation(&conversation_id) else { return; }; let my_user_id = state.store.meta(META_USER_ID).ok().flatten(); let mut pending = Vec::new(); for record in records { if !shown_in_view(¤t.mode, &record) { continue; } let Some(outgoing) = outgoing_of(&record) else { continue; }; let delivery = match record.state { OutboxState::Sending => Delivery::Sending, OutboxState::Failed => Delivery::Failed(record.last_error.unwrap_or_default()), }; let mut row = pending_row( record.id.clone(), conversation_id.clone(), my_user_id.clone(), record.created_at, &outgoing, delivery, ); row.reply_root = record.thread_root_id.clone(); pending.push((row, record.id, outgoing)); } for (row, id, outgoing) in pending { self.pending.push(row); self.pending_outgoing.insert(id, outgoing); } } fn discard_outbox_row(&self, id: &str, cx: &mut Context) { self.app.read(cx).store.delete_outbox(id).ok(); self.app .update(cx, |state, cx| state.refresh_local_previews(cx)); } fn delete_pending(&mut self, key: &str, cx: &mut Context) { self.pending.retain(|row| row.key != key); self.pending_outgoing.remove(key); self.discard_outbox_row(key, cx); self.rebuild(false, cx); } fn send(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context) { self.leave_detached(cx); self.send_as(new_outbox_id(), outgoing, None, window, cx); } fn send_in_thread( &mut self, root_id: String, outgoing: Outgoing, window: &mut Window, cx: &mut Context, ) { self.send_as(new_outbox_id(), outgoing, Some(root_id), window, cx); } fn send_as( &mut self, id: String, outgoing: Outgoing, reply_root: Option, window: &mut Window, cx: &mut Context, ) { let state = self.app.read(cx); let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); let Some(current) = self.current.as_ref() else { return; }; if mode.read_only || mode.demo { self.restore_unsent( "Read-only mode: nothing was sent", &outgoing, reply_root.as_deref(), window, cx, ); return; } let Some(engine) = engine else { self.discard_outbox_row(&id, cx); self.restore_unsent( "Not connected yet: nothing was sent", &outgoing, reply_root.as_deref(), window, cx, ); return; }; let conversation_id = current.selection.conversation_id().to_owned(); let (target, thread_root_id) = self.outbox_route(reply_root); let created_at = Utc::now(); self.push_pending( id.clone(), created_at, &outgoing, thread_root_id.clone(), cx, ); if let Some(record) = outbox_record( &id, &conversation_id, target, thread_root_id.as_deref(), &outgoing, created_at, ) { store.put_outbox(&record).ok(); } self.notice = None; self.rebuild(false, cx); if self.in_feed() { if thread_root_id.is_none() { self.scroller .update(cx, |scroller, cx| scroller.scroll_to_item(0, cx)); } } else { self.scroller .update(cx, |scroller, cx| scroller.scroll_to_end(cx)); } let receiver = runtime::spawn(async move { deliver( &engine, &conversation_id, target, thread_root_id.as_deref(), &outgoing, ) .await }); cx.spawn_in(window, async move |this, cx| { let result = receiver.await; this.update(cx, |this, cx| this.finish_send(&id, result, cx)) .ok(); }) .detach(); } fn restore_unsent( &mut self, message: &str, outgoing: &Outgoing, reply_root: Option<&str>, window: &mut Window, cx: &mut Context, ) { self.notice = Some(message.to_owned()); if let (Some(root_id), true) = (reply_root, self.in_feed()) { self.open_reply_editor(root_id.to_owned(), outgoing.reply.clone(), window, cx); if let Some(composer) = self.reply_composer.clone() { composer.update(cx, |composer, cx| composer.restore(outgoing, window, cx)); } } else { self.show_main_composer(cx); self.restore_subject(outgoing.subject.as_deref(), window, cx); self.composer .update(cx, |composer, cx| composer.restore(outgoing, window, cx)); } cx.notify(); } fn next_pending_key(&mut self) -> String { self.pending_counter += 1; format!("{PENDING_KEY_PREFIX}{}", self.pending_counter) } fn push_pending( &mut self, key: String, created_at: DateTime, outgoing: &Outgoing, reply_root: Option, cx: &App, ) { let my_user_id = self.row_context(cx).my_user_id; let conversation_id = self .current .as_ref() .map(|current| current.selection.conversation_id().to_owned()) .unwrap_or_default(); let mut row = pending_row( key.clone(), conversation_id, my_user_id, created_at, outgoing, Delivery::Sending, ); row.reply_root = reply_root; self.pending.push(row); self.pending_outgoing.insert(key, outgoing.clone()); } fn send_new_chat(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context) { let (recipients, topic) = { let draft = self.draft.read(cx); let topic = Some(draft.group_name(cx)).filter(|name| !name.is_empty()); (draft.chips().to_vec(), topic) }; if recipients.is_empty() { self.restore_unsent("Add at least one person first", &outgoing, None, window, cx); self.draft .update(cx, |draft, cx| draft.focus_query(window, cx)); return; } if self .pending .iter() .any(|row| matches!(row.delivery, Delivery::Sending)) { self.restore_unsent("Still creating the chat", &outgoing, None, window, cx); return; } let state = self.app.read(cx); let (mode, engine) = (state.mode, state.engine.clone()); if mode.read_only { self.restore_unsent( "Read-only mode: nothing was sent", &outgoing, None, window, cx, ); return; } if mode.demo && outgoing.has_attachments() { self.restore_unsent( "Read-only mode: nothing was sent", &outgoing, None, window, cx, ); return; } if mode.demo { self.send_demo_new_chat(&outgoing, &recipients, topic.as_deref(), cx); return; } let Some(engine) = engine else { self.restore_unsent( "Not connected yet: nothing was sent", &outgoing, None, window, cx, ); return; }; let user_ids: Vec = recipients.into_iter().map(|pick| pick.user_id).collect(); let known_chat = self .draft_created .as_ref() .filter(|(created_for, _)| *created_for == user_ids) .map(|(_, chat_id)| chat_id.clone()) .or_else(|| self.draft_target_chat(cx)); self.pending.clear(); self.pending_outgoing.clear(); self.draft_error = None; self.notice = None; let key = self.next_pending_key(); self.push_pending(key.clone(), Utc::now(), &outgoing, None, cx); self.rebuild(true, cx); let recipients_for_finish = user_ids.clone(); let receiver = runtime::spawn(async move { let chat_id = match known_chat { Some(chat_id) => chat_id, None => { let created = match user_ids.as_slice() { [user_id] => engine.create_one_on_one(user_id).await, _ => engine.create_group(&user_ids, topic.as_deref()).await, }; match created { Ok(chat_id) => chat_id, Err(error) => return (None, Some(short_error(&error))), } } }; let sent = engine .send_message_with_extras( &chat_id, &outgoing.html(), None, &outgoing.mentions, &outgoing.extras(), ) .await; if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) { let _ = engine .attach_link_preview(&chat_id, &record.message_id, preview) .await; } (Some(chat_id), sent.err().map(|error| short_error(&error))) }); cx.spawn_in(window, async move |this, cx| { let result = receiver.await; this.update_in(cx, |this, _, cx| { this.finish_new_chat(&key, recipients_for_finish, result, cx) }) .ok(); }) .detach(); } fn finish_new_chat( &mut self, key: &str, user_ids: Vec, result: Result<(Option, Option), tokio::sync::oneshot::error::RecvError>, cx: &mut Context, ) { if !self.draft_active || !self.pending.iter().any(|row| row.key == key) { return; } let (chat_id, error) = result.unwrap_or((None, Some("cancelled".to_owned()))); self.draft_created = chat_id.clone().map(|chat_id| (user_ids, chat_id)); match (chat_id, error) { (Some(chat_id), None) => { self.app.update(cx, |state, cx| { state.reload_sidebar(cx); state.select(Selection::Chat(chat_id), cx); }); } (created, error) => { if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { row.delivery = Delivery::Failed(error.unwrap_or_default()); } self.draft_error = Some( if created.is_some() { "Couldn't send the message." } else { "Couldn't create the chat." } .to_owned(), ); self.rebuild(false, cx); } } } fn send_demo_new_chat( &mut self, outgoing: &Outgoing, recipients: &[super::new_chat::Pick], topic: Option<&str>, cx: &mut Context, ) { let (store, chats) = { let state = self.app.read(cx); (state.store.clone(), state.sidebar.chats.clone()) }; let people: Vec<(String, String)> = recipients .iter() .map(|pick| (pick.user_id.clone(), pick.name.clone())) .collect(); let (chat, message) = match self.draft_target_chat(cx) { Some(chat_id) => { let Some(chat) = chats.iter().find(|chat| chat.id == chat_id) else { return; }; crate::demo::send_in_chat(chat, &outgoing.text(), &outgoing.html(), Utc::now()) } None => crate::demo::new_chat( &chats, &people, topic, &outgoing.text(), &outgoing.html(), Utc::now(), ), }; let _ = store.upsert_chats(std::slice::from_ref(&chat)); let _ = store.upsert_messages(std::slice::from_ref(&message)); self.app.update(cx, |state, cx| { state.reload_sidebar(cx); state.select(Selection::Chat(chat.id.clone()), cx); }); } fn conversation_id(&self) -> Option { self.current .as_ref() .map(|current| current.selection.conversation_id().to_owned()) } fn own_record(&self, message_id: &str, cx: &App) -> Option { let conversation_id = self.conversation_id()?; let my_user_id = self.row_context(cx).my_user_id?; self.app .read(cx) .store .messages_by_id(&conversation_id, &[message_id.to_owned()]) .ok()? .remove(message_id) .filter(|record| !record.deleted && record.sender_id.as_deref() == Some(&my_user_id)) } fn set_hover(&mut self, slot: HoverSlot, key: &str, hovered: bool, cx: &mut Context) { if hovered && matches!(slot, HoverSlot::Row) { self.request_post_follow(key, cx); } let pointer = self.pointer_on.slot(slot); if !hovered { if pointer.as_deref() == Some(key) { *pointer = None; } if !self.pointer_on.holds(key) && (self.hovered_message.as_deref() == Some(key) || self.toolbar_hovered.as_deref() == Some(key)) { self.leave_hover_later(key.to_owned(), cx); } return; } *pointer = Some(key.to_owned()); self.hover_leave_serial += 1; match slot { HoverSlot::Row => self.hovered_message = Some(key.to_owned()), HoverSlot::Toolbar => self.toolbar_hovered = Some(key.to_owned()), } if matches!(slot, HoverSlot::Row) && self .toolbar_hovered .as_deref() .is_some_and(|toolbar| toolbar != key) { self.toolbar_hovered = None; } if let Some(suppressed) = self.toolbar_suppressed.as_deref() && self.hovered_message.as_deref() != Some(suppressed) && self.toolbar_hovered.as_deref() != Some(suppressed) { self.toolbar_suppressed = None; } cx.notify(); } fn leave_hover_later(&mut self, key: String, cx: &mut Context) { self.hover_leave_serial += 1; let serial = self.hover_leave_serial; cx.spawn(async move |this, cx| { cx.background_executor().timer(HOVER_LEAVE_GRACE).await; this.update(cx, |this, cx| { if this.hover_leave_serial != serial || this.pointer_on.holds(&key) { return; } if this.hovered_message.as_deref() == Some(key.as_str()) { this.hovered_message = None; } if this.toolbar_hovered.as_deref() == Some(key.as_str()) { this.toolbar_hovered = None; } if this.toolbar_suppressed.as_deref() == Some(key.as_str()) { this.toolbar_suppressed = None; } cx.notify(); }) .ok(); }) .detach(); } fn suppress_toolbar(&mut self, key: &str, cx: &mut Context) { self.pointer_on.toolbar = None; if self.toolbar_hovered.as_deref() == Some(key) { self.toolbar_hovered = None; } self.toolbar_suppressed = Some(key.to_owned()); cx.notify(); } fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context) { if open { self.toolbar_pinned = Some(key.to_owned()); } else if self.toolbar_pinned.as_deref() == Some(key) { self.toolbar_pinned = None; } cx.notify(); } fn toolbar_visible(&self, key: &str, cx: &App) -> bool { let row_trigger = (!self.app.read(cx).actions_on_right_click) .then_some(self.hovered_message.as_deref()) .flatten(); self.toolbar_suppressed.as_deref() != Some(key) && self .toolbar_pinned .as_deref() .or(self.toolbar_hovered.as_deref()) .or(row_trigger) == Some(key) } pub(crate) fn context_menu_for(&self, key: &str) -> Option { self.context_menu.clone().filter(|open| open.key == key) } fn open_context_menu(&mut self, key: &str, position: Point, cx: &mut Context) { self.context_serial += 1; self.context_menu = Some(OpenContextMenu::new(key, position, self.context_serial)); cx.notify(); } fn close_context_menu(&mut self, from_outside: bool, cx: &mut Context) { let Some(open) = &self.context_menu else { return; }; if from_outside && self.toolbar_pinned.as_deref() == Some(open.key.as_str()) { return; } self.context_menu = None; cx.notify(); } fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context) { self.change_reaction(message_id, glyph, false, None, cx); } fn change_reaction( &mut self, message_id: &str, glyph: &str, only_add: bool, accepted_proposal: Option, cx: &mut Context, ) -> ReactionAttempt { let Some(conversation_id) = self.conversation_id() else { return ReactionAttempt::Blocked; }; let state = self.app.read(cx); let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); let engine = engine.filter(|_| !mode.read_only); if !mode.demo && engine.is_none() { self.show_notice("Read-only mode: reaction not sent", cx); return ReactionAttempt::Blocked; } let my_user_id = self.row_context(cx).my_user_id; let Some(mut record) = store .messages_by_id(&conversation_id, &[message_id.to_owned()]) .ok() .and_then(|mut found| found.remove(message_id)) else { return ReactionAttempt::MissingMessage; }; let wanted = reaction_glyph(glyph); let mut visible = teams_core::reactions(&record); apply_pending_reactions( &mut visible, self.pending_reactions.get(message_id), my_user_id.as_deref(), Utc::now(), ); let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref()); if only_add && !added { return ReactionAttempt::AlreadyThere; } let skin_tone = teams_core::skin_tone(&store); let wanted = if added { wanted } else { let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted); if emoticons::without_tone(&own) == own { emoticons::with_tone(&own, skin_tone) } else { own } }; let glyph = wanted.as_str(); let Some(engine) = engine.filter(|_| !mode.demo) else { let mut reactions = teams_core::reactions(&record); set_own_reaction( &mut reactions, glyph, my_user_id.as_deref(), added, Utc::now(), ); record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default(); let _ = store.upsert_messages(std::slice::from_ref(&record)); if added { self.record_reaction_use(glyph, cx); } self.rebuild(false, cx); return ReactionAttempt::Acted; }; let entries = self .pending_reactions .entry(message_id.to_owned()) .or_default(); entries.retain(|(pending, _)| { emoticons::without_tone(pending) != emoticons::without_tone(&wanted) }); entries.push((wanted.clone(), added)); self.rebuild(false, cx); let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned()); let reaction_type = api_reaction(&wanted); let receiver = runtime::spawn({ let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone()); async move { if added { engine .set_reaction(&conversation_id, &message_id, &reaction_type) .await } else { engine .unset_reaction(&conversation_id, &message_id, &reaction_type) .await } } }); cx.spawn(async move |this, cx| { let outcome = match receiver.await { Ok(Ok(())) => Ok(()), Ok(Err(error)) => Err(short_error(&error)), Err(_) => Err("cancelled".to_owned()), }; this.update(cx, |this, cx| { this.finish_reaction( &conversation_id, &message_id, &glyph, added, accepted_proposal.as_deref(), outcome, cx, ) }) .ok(); }) .detach(); ReactionAttempt::Started } fn finish_reaction( &mut self, conversation_id: &str, message_id: &str, glyph: &str, added: bool, accepted_proposal: Option<&str>, outcome: Result<(), String>, cx: &mut Context, ) { let wanted = reaction_glyph(glyph); let store = self.app.read(cx).store.clone(); if let Some(proposal_id) = accepted_proposal.filter(|_| outcome.is_ok()) { crate::agent_api::resolve_reaction_proposal( conversation_id, message_id, proposal_id, mcp::ReactionOutcome::Accepted, cx, ); } if outcome.is_ok() { let my_user_id = self.row_context(cx).my_user_id; if let Some(mut record) = store .messages_by_id(conversation_id, &[message_id.to_owned()]) .ok() .and_then(|mut found| found.remove(message_id)) { let mut reactions = teams_core::reactions(&record); set_own_reaction( &mut reactions, glyph, my_user_id.as_deref(), added, Utc::now(), ); record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default(); let _ = store.upsert_messages(std::slice::from_ref(&record)); } if added { self.record_reaction_use(glyph, cx); } } if let Some(entries) = self.pending_reactions.get_mut(message_id) { entries.retain(|entry| *entry != (wanted.clone(), added)); if entries.is_empty() { self.pending_reactions.remove(message_id); } } self.rebuild(false, cx); if let Err(error) = outcome { self.show_notice(&format!("Reaction failed: {error}"), cx); } } fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context) { if chatsvc::custom_emoji(glyph).is_some() { return; } let store = self.app.read(cx).store.clone(); self.recent.update(cx, |recent, cx| { recent.reload(&store); recent.record_use(&emoticons::without_tone(glyph)); recent.save(&store); cx.notify(); }); } fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context) { let Some(record) = self.own_record(message_id, cx) else { return; }; let edit = EditPreview { message_id: record.message_id.clone(), excerpt: reply_excerpt(&record), scheduled: None, }; let in_chat = matches!( self.current.as_ref().map(|current| ¤t.selection), Some(Selection::Chat(_)) ); let mentions = if in_chat { teams_core::user_mention_inputs(&record) } else { Vec::new() }; let draft = Outgoing { banner: None, draft: message_draft(&record), subject: None, mentions, reply: None, edit: Some(edit), images: Vec::new(), files: Vec::new(), link_preview: None, importance: Default::default(), }; self.show_main_composer(cx); self.composer .update(cx, |composer, cx| composer.begin_edit(draft, window, cx)); } fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context) { if self.draft_active { return; } let key = self .rows .borrow() .iter() .flat_map(Row::messages) .filter(|message| { message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX) }) .max_by_key(|message| message.created_at) .map(|message| message.key.clone()); if let Some(key) = key { self.begin_edit(&key, window, cx); } } fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context) { let Some(edit) = outgoing.edit.clone() else { return; }; let Some(conversation_id) = self.conversation_id() else { return; }; let state = self.app.read(cx); let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone()); if mode.demo { if let Some(mut record) = self.own_record(&edit.message_id, cx) { record.body_html = outgoing.html(); record.edited_at = Some(Utc::now()); let _ = store.upsert_messages(std::slice::from_ref(&record)); self.rebuild(false, cx); } return; } let Some(engine) = engine.filter(|_| !mode.read_only) else { self.notice = Some("Read-only mode: edit not saved".to_owned()); self.show_main_composer(cx); self.composer .update(cx, |composer, cx| composer.restore(&outgoing, window, cx)); cx.notify(); return; }; let original = self.own_record(&edit.message_id, cx); if let Some(mut record) = original.clone() { record.body_html = outgoing.html(); record.edited_at = Some(Utc::now()); let _ = store.upsert_messages(std::slice::from_ref(&record)); } let message_id = edit.message_id.clone(); self.saving_edits.insert(message_id.clone()); self.rebuild(false, cx); let sent = outgoing.clone(); let edited_conversation = conversation_id.clone(); let receiver = runtime::spawn(async move { engine .edit_message_html( &conversation_id, &edit.message_id, &sent.html(), &sent.mentions, ) .await }); cx.spawn_in(window, async move |this, cx| { let failed = !matches!(receiver.await, Ok(Ok(()))); this.update_in(cx, |this, window, cx| { this.saving_edits.remove(&message_id); if failed && let Some(record) = &original { let _ = store.upsert_messages(std::slice::from_ref(record)); } this.rebuild(false, cx); let same_chat = this.conversation_id().as_deref() == Some(&*edited_conversation); if failed && !same_chat { this.notice = Some("Edit failed".to_owned()); cx.notify(); } else if failed { this.show_main_composer(cx); if !this.composer.read(cx).is_editing() { this.notice = Some("Edit failed: your text is back in the composer".to_owned()); this.composer.update(cx, |composer, cx| { composer.begin_edit(outgoing.clone(), window, cx) }); } else { this.notice = Some("Edit failed".to_owned()); } cx.notify(); } }) .ok(); }) .detach(); } fn copy_text(&self, message_id: &str, cx: &mut Context) { let Some(conversation_id) = self.conversation_id() else { return; }; let record = self .app .read(cx) .store .messages_by_id(&conversation_id, &[message_id.to_owned()]) .ok() .and_then(|mut found| found.remove(message_id)); if let Some(record) = record { cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record))); } } fn refresh_card( &mut self, key: &str, card_index: usize, action: ExecuteAction, cx: &mut Context, ) { let Some(conversation_id) = self.conversation_id() else { return; }; let scope = CardScope::message(&conversation_id, key, card_index); self.app.update(cx, |state, cx| { state.refresh_card_manually(scope, action, cx) }); } pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context) { let Some(conversation_id) = self.conversation_id() else { return; }; self.app.update(cx, |state, cx| { state.translate_message(&conversation_id, key, cx) }); } fn show_notice(&mut self, message: &str, cx: &mut Context) { self.app.update(cx, |state, cx| { state.raise_notice(message.to_owned(), None, cx) }); } fn delegate_entries(&self, key: &str, cx: &App) -> (Vec, Option) { let (Some(conversation_id), Some(runs)) = (self.conversation_id(), crate::agents::runs_handle(cx)) else { return (Vec::new(), None); }; if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) { return (Vec::new(), None); } let settings = runs.read(cx).settings(); let entries: Vec = settings .actions .iter() .map(|action| { let request = StartRequest { action_id: action.id.clone(), conversation_id: conversation_id.clone(), message_id: key.to_owned(), }; let agent_name = settings .agents .iter() .find(|agent| agent.id == action.agent_id) .map(|agent| agent.name.clone()) .unwrap_or_default(); DelegateEntry { label: action.label.clone(), agent_name, action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)), } }) .collect(); let manage_agents = (!entries.is_empty()).then(|| { Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action }); (entries, manage_agents) } fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet) { let Some(conversation_id) = self.conversation_id() else { return (false, HashSet::new()); }; let Some(runs) = crate::agents::runs_handle(cx) else { return (false, HashSet::new()); }; let mut snapshot: HashMap = HashMap::new(); for run in runs.read(cx).for_conversation(&conversation_id) { snapshot.insert(run.message_id.clone(), run.clone()); } let layouts: HashMap = snapshot .iter() .map(|(key, run)| (key.clone(), run.layout_key())) .collect(); let layout_changed: HashSet = layouts .iter() .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout)) .map(|(key, _)| key.clone()) .chain( self.agent_layouts .keys() .filter(|key| !layouts.contains_key(*key)) .cloned(), ) .collect(); self.agent_layouts = layouts; let snapshot_changed = *self.agent_runs.borrow() != snapshot; *self.agent_runs.borrow_mut() = snapshot; (snapshot_changed, layout_changed) } fn sync_agent_chips(&mut self, cx: &mut Context) { let (snapshot_changed, changed) = self.refresh_agent_runs(cx); let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running); self.remeasure_rows_of(&changed, cx); if snapshot_changed || any_running { cx.notify(); } } fn remeasure_rows_of(&mut self, keys: &HashSet, cx: &mut Context) { if keys.is_empty() { return; } let indices: Vec = self .rows .borrow() .iter() .enumerate() .filter(|(_, row)| row.messages().any(|message| keys.contains(&message.key))) .map(|(index, _)| index) .collect(); self.scroller.update(cx, |scroller, cx| { for index in indices { scroller.remeasure_items(index..index + 1, cx); } }); } fn message_menu( &self, message: &MessageRow, mine: HashSet, refresh: Option<(usize, ExecuteAction)>, view: WeakEntity, cx: &App, ) -> MessageMenu { let (key, own) = (message.key.as_str(), message.own); let translate_label = match message.translation { Some(TranslationLine::Translated { showing_original: false, .. }) => "See original", Some(TranslationLine::Translated { .. }) => "See translation", _ => "Translate", }; let action = |run: fn(&mut Self, &str, &mut Window, &mut Context)| -> Action { let (view, key) = (view.clone(), key.to_owned()); Rc::new(move |window, cx| { view.update(cx, |this, cx| { this.set_pinned(&key, false, cx); run(this, &key, window, cx) }) .ok(); }) }; let react: PickHandler = { let (view, key) = (view.clone(), key.to_owned()); Rc::new(move |glyph, _, cx| { view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx)) .ok(); }) }; let hover = { let (view, key) = (view.clone(), key.to_owned()); Rc::new(move |hovered: bool, cx: &mut App| { view.update(cx, |this, cx| { this.set_hover(HoverSlot::Toolbar, &key, hovered, cx) }) .ok(); }) }; let pin = { let (view, key) = (view.clone(), key.to_owned()); Rc::new(move |open: bool, _: &mut Window, cx: &mut App| { view.update(cx, |this, cx| this.set_pinned(&key, open, cx)) .ok(); }) }; let refresh_card = refresh.map(|(card_index, refresh_action)| { let (view, key) = (view.clone(), key.to_owned()); Rc::new(move |_: &mut Window, cx: &mut App| { view.update(cx, |this, cx| { this.refresh_card(&key, card_index, refresh_action.clone(), cx) }) .ok(); }) as Action }); let chat_id = self.chat_id(); let state = self.app.read(cx); let saved = self .conversation_id() .is_some_and(|conversation_id| state.is_saved(&conversation_id, key)); let quick = state.quick_reactions(); let in_chat = chat_id.is_some(); let pin_conversation_id = self.pin_conversation_id(); let pinned = pin_conversation_id .as_deref() .is_some_and(|conversation_id| state.is_pinned(conversation_id, key)); let pinnable = in_chat || pin_conversation_id.as_deref().is_some_and(|channel_id| { state .message_record(channel_id, key) .is_some_and(|record| record.reply_to_id.is_none()) }); let (delegate, manage_agents) = self.delegate_entries(key, cx); let post_followed = self.post_follow(key, cx); MessageMenu { key: key.to_owned(), react, reply: Some(action(|this, key, window, cx| { this.begin_reply(key, window, cx) })), forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))), forward_multiple: in_chat .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))), copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))), copy: action(|this, key, _, cx| this.copy_text(key, cx)), translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))), translate_label, share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))), save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))), saved, toggle_pinned: pinnable .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))), pinned, toggle_follow: post_followed .map(|_| action(|this, key, _, cx| this.toggle_post_follow(key, cx))), followed: post_followed.unwrap_or_default(), edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))), delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))), mark_unread: (in_chat && !own) .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))), refresh_card, delegate, manage_agents, kvt: crate::kvt::menu_entries(self.conversation_id(), key, cx), pin, hover, picker: self.picker.clone(), quick, mine, done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)), } } fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context) { let Some(outgoing) = self.pending_outgoing.remove(key) else { return; }; let reply_root = self .pending .iter() .find(|row| row.key == key) .and_then(|row| row.reply_root.clone()); self.pending.retain(|row| row.key != key); if self.draft_active { self.send_new_chat(outgoing, window, cx); } else { self.send_as(key.to_owned(), outgoing, reply_root, window, cx); } } fn finish_send( &mut self, key: &str, result: Result, tokio::sync::oneshot::error::RecvError>, cx: &mut Context, ) { if matches!(result, Ok(Ok(Delivered::WithoutBanner))) { self.notice = Some(POSTED_WITHOUT_BANNER.to_owned()); } if let Ok(Ok(Delivered::Complete { message_id: Some(message_id), })) = &result { self.keep_sent_previews(key, message_id); crate::views::jumbo_emoji::hand_over_sent(key, message_id, cx); } let failure = match result { Ok(Ok(_)) => None, Ok(Err(error)) => Some(short_error(&error)), Err(error) => Some(short_error(&error)), }; let store = self.app.read(cx).store.clone(); match failure { None => { store.delete_outbox(key).ok(); self.pending.retain(|row| row.key != key); self.pending_outgoing.remove(key); } Some(error) => { store.mark_outbox_failed(key, &error).ok(); if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) { row.delivery = Delivery::Failed(error.clone()); self.notice = Some(format!("Not sent: {error}")); } } } self.app .update(cx, |state, cx| state.refresh_local_previews(cx)); self.rebuild(false, cx); } fn keep_sent_previews(&mut self, pending_key: &str, message_id: &str) { let Some(row) = self.pending.iter().find(|row| row.key == pending_key) else { return; }; if row.local_images.is_empty() { return; } self.sent_previews .push_back((message_id.to_owned(), row.local_images.clone())); if self.sent_previews.len() > SENT_PREVIEWS_KEPT { self.sent_previews.pop_front(); } } fn render_drop_overlay(&self, cx: &mut Context) -> impl IntoElement { let target = match self.current.as_ref().map(|current| ¤t.selection) { Some(Selection::Chat(_)) => DropTarget::Chat, Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library, Some(Selection::Channel(_)) => DropTarget::Channel, None => DropTarget::NewChat, }; let title = self .current .as_ref() .map(|current| current.title.as_str()) .unwrap_or_default(); let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1)); let composer = self.composer.clone(); div() .id("drop-overlay") .absolute() .top_0() .left_0() .size_full() .opacity(0.) .bg(theme::drop_background()) .drag_over::(move |style, _, _, cx| { if composer.read(cx).is_editing() { style } else { style.opacity(1.) } }) .on_drag_move( cx.listener(|this, event: &DragMoveEvent, _, cx| { let count = event.drag(cx).paths().len(); if this.drag_file_count != count { this.drag_file_count = count; cx.notify(); } }), ) .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| { let paths = dropped.paths().to_vec(); if this.shared_active() { this.upload_paths(paths, cx); return; } this.composer .update(cx, |composer, cx| composer.add_paths(paths, window, cx)); })) .child( div() .absolute() .inset(px(12.)) .rounded(px(12.)) .border_2() .border_color(theme::accent()) .flex() .items_center() .justify_center() .child( v_flex() .items_center() .gap(px(6.)) .px(px(24.)) .py(px(16.)) .rounded(px(12.)) .bg(black().opacity(0.55)) .child(symbol("upload", 28., theme::accent_text())) .child( div() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text_strong()) .child(heading), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(detail), ), ), ) } fn render_draft_error(&self, cx: &mut Context) -> Option
{ let message = self.draft_error.clone()?; let failed_key = self .pending .iter() .find(|row| matches!(row.delivery, Delivery::Failed(_))) .map(|row| row.key.clone())?; Some( h_flex() .w_full() .flex_none() .px(px(20.)) .py(px(4.)) .gap(px(8.)) .items_center() .text_size(px(12.)) .text_color(theme::red_soft()) .child(message) .child( Button::new("retry-new-chat") .ghost() .compact() .label(tr("common.retry")) .on_click(cx.listener(move |this, _, window, cx| { this.retry(&failed_key, window, cx) })), ), ) } pub fn open_find(&mut self, window: &mut Window, cx: &mut Context) { if self.pinned || self.draft_active { return; } let Some(selection) = self .current .as_ref() .map(|current| current.selection.clone()) else { return; }; self.channel_details_open = false; self.close_copilot(); if let Some(panel) = &self.find_panel { panel.update(cx, |panel, cx| panel.focus(window, cx)); return; } let app = self.app.clone(); let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx)); let subscription = cx.subscribe_in( &panel, window, move |this, _, event: &FindPanelEvent, window, cx| match event { FindPanelEvent::Close => this.close_find(window, cx), FindPanelEvent::Jump(message_id) => { let (selection, message_id) = (selection.clone(), message_id.clone()); this.app.update(cx, |state, cx| { state.jump_to_message(selection, message_id, cx) }); } }, ); panel.update(cx, |panel, cx| panel.focus(window, cx)); self.find_panel = Some(panel); self.find_subscription = Some(subscription); cx.notify(); } fn close_find(&mut self, window: &mut Window, cx: &mut Context) { self.find_panel = None; self.find_subscription = None; self.composer .update(cx, |composer, cx| composer.focus(window, cx)); cx.notify(); } fn header_width(&self, window: &Window) -> f32 { match self.header_width.get() { width if width > 0. => width, _ => { f32::from(window.viewport_size().width) - RAIL_WIDTH - SIDEBAR_WIDTH - 2. * ISLAND_GAP } } } fn tabs_below_title(&self, window: &Window) -> bool { self.header_width(window) < TABS_INLINE_MIN_WIDTH } fn render_header( &self, current: &Current, tabs: Option, cx: &mut Context, ) -> impl IntoElement { let app = self.app.read(cx); let directory = &app.directory; let me = directory.me.as_ref(); let mut lead: Option = None; let mut subline = String::new(); let mut stack: Option = None; let mut rename: Option = None; let mut names_title: Option
= None; let mut external: Option
= None; let mut header_title = current.title.clone(); match ¤t.selection { Selection::Chat(chat_id) => { if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) { let faces = others(chat, me); let face = |(user_id, name): (Option, String)| Face { user_id, name }; let first = faces.first().cloned().map(face); if let Some(bot) = one_on_one_bot(chat, me) { lead = Some(bot_tile(directory, &face(bot), 36.)); } else if is_one_on_one(chat) || faces.len() < 2 { let name = first .as_ref() .map_or(current.title.as_str(), |face| face.name.as_str()); let user_id = first.as_ref().and_then(|face| face.user_id.as_deref()); let avatar = person_avatar(directory, user_id, name, 36.); let presence = user_id.map(|id| directory.presence_of(id)); let avatar = match presence { Some(kind) => with_presence(avatar, kind, 36., theme::surface()) .into_any_element(), None => avatar, }; lead = Some( opens_profile(div().id("header-avatar").flex_none(), user_id) .child(avatar) .into_any_element(), ); subline = match (user_id, presence) { (Some(id), Some(presence)) => { directory.status_label(id, presence).to_owned() } _ => String::new(), }; if is_one_on_one(chat) && !is_notes_chat(chat_id) { stack = Some(add_people_button(&self.app, chat_id)); } if user_id.is_some_and(|id| directory.is_external(id)) { external = Some(chat_header_actions::external_badge()); } } else { if chat.kind == GROUP_KIND && me.is_some_and(|me| { chat.members .iter() .any(|member| member.user_id.as_deref() == Some(&me.user_id)) }) { rename = Some(group_name_button( &self.app, &self.group_name, chat_id, &chat.title, )); } if chat.title.trim().is_empty() { names_title = Some(chat_header_actions::group_title(directory, &faces)); } let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone())); lead = Some(spec_avatar(directory, &pair, 36., theme::surface())); stack = Some(members_popover( &self.app, chat_id, chat_header_actions::member_count(chat.members.len()) .debug_selector(|| MEMBERS_BUTTON.into()), )); } } } Selection::Channel(channel_id) => { let team = app.sidebar.teams.iter().find(|entry| { entry .channels .iter() .any(|channel| &channel.id == channel_id) }); let (name, key) = team .map_or((current.title.as_str(), current.title.as_str()), |entry| { (entry.team.name.as_str(), entry.team.id.as_str()) }); let photo = team.and_then(|entry| { app.directory .avatar(&teams_core::team_avatar_key(&entry.team.id)) }); lead = Some(team_avatar(photo, name, key, 36., 9.)); if let Some(channel) = team.and_then(|entry| { entry .channels .iter() .find(|channel| &channel.id == channel_id) }) { header_title = channel.name.clone(); } } } let mut header = h_flex() .w_full() .h(px(HEADER_HEIGHT)) .flex_none() .px(px(HEADER_PADDING)) .gap(px(HEADER_GAP)) .items_center(); if matches!(current.mode, ViewMode::Thread(_)) { header = header.child( h_flex() .id("back-to-channel") .flex_none() .gap(px(2.)) .pl(px(4.)) .pr(px(8.)) .py(px(4.)) .items_center() .rounded(px(6.)) .cursor_pointer() .text_size(px(13.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::accent_text()) .hover(|button| button.bg(theme::row_hover())) .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx))) .child(icon(IconName::ChevronLeft, 16., theme::accent_text())) .child("Back to channel"), ); } let channel_note = match current.mode { ViewMode::Flat => None, ViewMode::ThreadList => Some("Posts"), ViewMode::Thread(_) => Some("Conversation"), }; if let Some(note) = channel_note { subline = note.to_owned(); } let call_controls = if self.pinned && !self.popped_out { Vec::new() } else { header_call_controls(&self.app, app, ¤t.selection, self.header_overflows()) }; let sync = ¤t.sync; let loading_window = current.window_request.is_some(); if sync.failed { subline = "Not up to date".to_owned(); } else if loading_window { subline = "Loading message ...".to_owned(); } else if sync.shown_at.is_some() { subline = if sync.slow { "Taking longer than usual ..." } else { "Loading messages ..." } .to_owned(); } let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs)); let overflow = self.header_overflows(); let divided = !overflow && matches!(current.selection, Selection::Chat(_)) && (!call_controls.is_empty() || stack.is_some()); header .relative() .child(record_width(&self.header_width)) .when(sync.shown_at.is_some() || loading_window, |header| { header.child(progress_bar()) }) .when(overflow, |header| header.gap(px(HEADER_COMPACT_GAP))) .when(!overflow, |header| header.children(lead)) .child( v_flex() .map(|column| match inline_tabs { Some(_) => column.flex_shrink(1.).max_w(px(HEADER_TITLE_MAX_WIDTH)), None => column.flex_1(), }) .min_w_0() .overflow_hidden() .gap(px(1.)) .child( h_flex() .min_w_0() .gap(px(2.)) .items_center() .child( div() .truncate() .text_size(px(15.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text()) .map(|title| match names_title { Some(names) => title.child(names), None => title.child(header_title), }), ) .children(external) .children(rename), ) .when(!subline.is_empty(), |column| { column.child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child(subline), ) }), ) .children(inline_tabs) .children(call_controls) .children(stack) .when(divided, |header| header.child(header_divider())) .when(!overflow, |header| { header .children(self.copilot_button(cx)) .children(self.chat_find_button(cx)) }) .children(self.channel_find_button(cx)) .when(!overflow, |header| { header.children(self.channel_details_button(cx)) }) .children(self.channel_more_button(cx)) .children(self.chat_more_button(overflow, cx)) .children(self.pop_in_button(current)) } fn pop_in_button(&self, current: &Current) -> Option { let Selection::Chat(chat_id) = ¤t.selection else { return None; }; if !self.popped_out { return None; } let (app, chat_id) = (self.app.clone(), chat_id.clone()); Some( Button::new("chat-pop-in") .icon(IconName::SquareArrowDownLeft) .ghost() .size(px(POP_IN_BUTTON_SIZE)) .rounded(px(8.)) .tooltip(chat_pop_out::POP_IN_TOOLTIP) .on_click(move |_, window, cx| { chat_pop_out::return_to_main_window(&app, &chat_id, window, cx) }) .into_any_element(), ) } } const GROUP_KIND: &str = "group"; const HEADER_DIVIDER_HEIGHT: f32 = 20.; fn header_divider() -> Div { div() .w(px(1.)) .h(px(HEADER_DIVIDER_HEIGHT)) .mx(px(4.)) .flex_none() .bg(theme::border()) } impl Render for ConversationView { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let background = theme::surface(); let mut root = v_flex() .when(!self.pinned, |root| { root.debug_selector(|| "shell/islands/main".into()) }) .flex_1() .w_full() .min_w_0() .h_full() .rounded(px(10.)) .bg(background) .overflow_hidden() .track_focus(&self.focus_handle); let drafting = self.draft_active; if self.current.is_none() && !drafting { return root .items_center() .justify_center() .text_color(theme::text_muted()) .child("Select a chat or channel") .into_any_element(); } let in_feed = self.in_feed(); let detached = self.is_detached(); let rows_seen = self.feed_rows_seen.replace(usize::MAX); if in_feed && rows_seen != usize::MAX { self.feed_at_top = rows_seen == 0; } let forward_selection = self.active_forward_selection(cx); let rows = self.rows.clone(); let rows_seen = self.feed_rows_seen.clone(); let env = RenderEnv { view: cx.weak_entity(), app: self.app.clone(), highlighted: self.highlighted_message.clone(), drafting, reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()), timeline: self.timeline_bounds.clone(), agent_runs: self.agent_runs.clone(), reaction_proposals: self.reaction_proposals.clone(), forward_selection: forward_selection.clone(), appearing: self.appear_tracker.entering(Instant::now()), }; let pin_banner = self .render_pin_banner(cx) .filter(|_| !drafting && !self.shared_active() && !self.recap_active()); let timeline_top_inset = pin_banner_inset(pin_banner.is_some()); let comfy = self.app.read(cx).account_chat_settings().message_density != teams_core::MessageDensity::Compact; let typing_line = self.render_typing_line(cx); let typing_offset = { let scroller = self.scroller.read(cx); let last_row = scroller.item_count().checked_sub(1); let offset = typing_bottom_offset( self.timeline_bounds.get(), last_row.and_then(|index| scroller.item_bounds(index)), self.typing_offset.get(), ); self.typing_offset.set(offset); offset }; let scroller = MessageScroller::new( "messages", self.scroller.clone(), move |index, window, cx| { rows_seen.set(rows_seen.get().min(index)); let rows = rows.borrow(); let row = match rows.get(index) { Some(Row::Message(message)) => { let actions = env.message_actions(message, window, cx); let state = env.app.read(cx); render_message_row(message, index, actions, &state.directory, cx) } Some(Row::Post(post)) => { let actions = env.post_actions(post, window, cx); let state = env.app.read(cx); render_post(post, index, actions, &state.directory, cx) } Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index), Some(Row::LoadOlder) => { let view = env.view.clone(); cx.defer(move |cx| { view.update(cx, |this, cx| this.request_older(cx)).ok(); }); h_flex() .w_full() .py_2() .gap(px(6.)) .justify_center() .text_size(px(12.)) .text_color(theme::text_muted()) .child(icon(IconName::Loader, 12., theme::text_muted())) .child("Loading older messages") .into_any_element() } Some(Row::LoadNewer) => { let view = env.view.clone(); cx.defer(move |cx| { view.update(cx, |this, cx| { this.request_window_page(WindowDirection::Forward, cx) }) .ok(); }); h_flex() .w_full() .py_2() .gap(px(6.)) .justify_center() .text_size(px(12.)) .text_color(theme::text_muted()) .child(icon(IconName::Loader, 12., theme::text_muted())) .child("Loading newer messages") .into_any_element() } Some(Row::Start(start)) => { let state = env.app.read(cx); v_flex() .w_full() .items_center() .gap(px(8.)) .pt(px(32.)) .pb(px(16.)) .child(match start.user_id.as_deref() { Some(user_id) if is_bot_id(user_id) => bot_tile( &state.directory, &Face { user_id: Some(user_id.to_owned()), name: start.title.clone(), }, 56., ), user_id => person_avatar( &state.directory, user_id, &start.avatar_name, 56., ), }) .child( div() .text_size(px(16.)) .font_weight(FontWeight::SEMIBOLD) .text_color(theme::text()) .child(start.title.clone()), ) .child( div() .text_size(px(12.)) .text_color(theme::text_muted()) .child("This is the beginning of the conversation"), ) .into_any_element() } None => div().into_any_element(), }; runway(row, comfy) }, ) .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.))) .wheel_mask(false) .jump_button(!in_feed) .force_jump_button(detached) .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL) .with_jump_button_renderer(|button| { button .label(jump::JUMP_TO_NEWEST_LABEL) .tooltip(jump::jump_to_newest_tooltip()) .border_0() .bg(theme::accent()) .text_color(theme::on_accent()) }) .when(detached, |scroller| { let view = cx.weak_entity(); scroller.on_jump(move |_, cx| { view.update(cx, |this, cx| this.leave_detached(cx)).ok(); }) }) .with_list_style(StyleRefinement::default().pb(px(if typing_line.is_some() { TYPING_TOP_GAP + TYPING_BUBBLE_HEIGHT + TYPING_BOTTOM_GAP } else if in_feed { 0. } else { COMPOSER_TOP_GAP }))) .with_top_inset(timeline_top_inset); root = match self.current.as_ref().filter(|_| !drafting) { Some(current) => { let tab_bar = self .render_tab_bar(window, cx) .or_else(|| self.render_chat_tab_bar(cx)); let (inline_tabs, tabs_row) = match tab_bar { Some(tabs) if self.tabs_below_title(window) => (None, Some(tabs)), tabs => (tabs, None), }; root.child(self.render_header(current, inline_tabs, cx)) .children(tabs_row.map(|tabs| { h_flex() .w_full() .h(px(TABS_ROW_HEIGHT)) .flex_none() .px(px(HEADER_PADDING)) .child(tabs) })) .child(edge_divider(HEADER_DIVIDER)) } None => root.child(self.draft.clone()), }; let sync_failed = self .current .as_ref() .is_some_and(|current| current.sync.failed); if let Some(notice) = &self.notice { root = root.child( h_flex() .px(px(20.)) .py_1() .gap(px(8.)) .items_center() .text_xs() .bg(theme::amber().opacity(0.15)) .text_color(theme::amber()) .child(div().flex_1().min_w_0().child(notice.clone())) .when(sync_failed, |bar| { bar.child( Button::new("retry-fetch") .ghost() .compact() .label(tr("common.retry")) .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))), ) }), ); } let recap_active = self.recap_active(); let empty_channel = in_feed && self.rows.borrow().is_empty(); let new_post = self.render_new_post(cx); self.watch_feed_scroll(cx); let feed_scrolled = new_post.is_some() && self.scroller.read(cx).is_scrolled_from_top(); let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() { let draft = self.draft.read(cx); let group_name = draft.group_name(cx); draft.render_empty(&self.app.read(cx).directory, &group_name) } else if self.shared_active() { self.render_shared(cx) } else if self.recap_active() { self.render_recap(cx) } else if let Some(start) = self.notes_space() { notes_space::render_notes_space(&self.app.read(cx).directory, &start) } else if empty_channel { div() .size_full() .flex() .items_center() .justify_center() .text_size(px(13.)) .text_color(theme::text_muted()) .child("No posts in this channel yet") .into_any_element() } else { scroller.into_any_element() }; let channel_details = self.render_channel_details(cx); let copilot_island = self.render_copilot(cx); let find_panel = self.find_panel.clone().filter(|_| !drafting); let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH; let content = v_flex() .relative() .flex_1() .min_w_0() .min_h_0() .children(new_post.map(|post| runway(post, comfy))) .child( div() .debug_selector(|| TIMELINE_TAG.into()) .relative() .flex_1() .min_h_0() .child(record_bounds(&self.timeline_bounds, timeline_top_inset)) .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx))) .child(body) .children(typing_line.map(|line| { div() .absolute() .left_0() .right_0() .bottom(px(typing_offset)) .child(runway(line, comfy)) })) .when(feed_scrolled, |timeline| { timeline.child( edge_divider(FEED_EDGE_TAG) .absolute() .top_0() .left_0() .right_0(), ) }) .children(pin_banner.map(|banner| pin_banner_overlay(runway(banner, comfy)))), ) .children( self.render_draft_error(cx) .map(|error| runway(error, comfy)), ) .when( !in_feed && !recap_active && !self.shared_active(), |column| match &forward_selection { Some(snapshot) => { column.child(runway(self.render_forward_footer(snapshot, cx), comfy)) } None => { column.child(runway( v_flex() .w_full() .children(self.render_absence_notice(cx)) .children(self.render_proposal_card(cx).map(|card| { div().w_full().pb(px(COMPOSER_TOP_GAP)).child(card) })) .child(self.composer.clone()), comfy, )) } }, ) .child(self.render_drop_overlay(cx)); let root = root .child( h_flex() .relative() .flex_1() .min_h_0() .w_full() .items_stretch() .child(content) .children(channel_details) .children(find_panel.map(|panel| { div() .h_full() .w(px(FIND_PANEL_WIDTH)) .min_w_0() .flex_shrink(1.) .when(find_overlays, |slot| { slot.absolute().top_0().right_0().bottom_0().max_w_full() }) .child(panel) })), ) .capture_action(cx.listener(|this, _: &Escape, _, cx| { if this.reaction_details.is_some() { this.close_reaction_details(cx); cx.stop_propagation(); } })) .on_action(cx.listener(|this, _: &Escape, window, cx| { if this.draft_active { if this.draft.read(cx).has_focus(window, cx) { this.draft.update(cx, |draft, cx| draft.escape(cx)); } } else if this.cancel_forward_selection(cx) { } else if !this.on_escape(window, cx) { cx.propagate(); } })); let root = root.child(crate::inline_video::sentinel()); match copilot_island { Some(island) => h_flex() .size_full() .min_w_0() .gap(px(ISLAND_GAP)) .child(root) .child(island) .into_any_element(), None => root.into_any_element(), } } } /// Right under the last row like one more message; once that row scrolls below the view it sticks above the composer. /// A row added or replaced since the last frame has no bounds yet, so the bubble keeps its previous place. fn typing_bottom_offset( timeline: Option>, last_row: Option>, previous: f32, ) -> f32 { let (Some(timeline), Some(last_row)) = (timeline, last_row) else { return previous; }; let under_last_row = f32::from(timeline.bottom() - last_row.bottom()) - TYPING_TOP_GAP - TYPING_BUBBLE_HEIGHT; under_last_row.max(TYPING_BOTTOM_GAP) } fn typing_dots() -> impl IntoElement { h_flex() .gap(px(3.)) .flex_none() .children((0..TYPING_DOT_COUNT).map(|index| { let phase_offset = index as f32 / TYPING_DOT_COUNT as f32; div() .size(px(TYPING_DOT_SIZE)) .rounded_full() .bg(theme::text_muted()) .with_animation( ElementId::NamedInteger("typing-dot".into(), index as u64), Animation::new(TYPING_PULSE_PERIOD).repeat(), move |dot, delta| { let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs(); dot.opacity(0.3 + 0.7 * wave) }, ) })) } fn record_width(width: &Rc>) -> impl IntoElement { let width = width.clone(); canvas( move |bounds, window, _| { let measured = f32::from(bounds.size.width); if (measured - width.replace(measured)).abs() > 0.5 { window.request_animation_frame(); } }, |_, _, _, _| {}, ) .absolute() .top_0() .left_0() .size_full() } fn progress_bar() -> impl IntoElement { div() .absolute() .left_0() .right_0() .bottom(px(-1.)) .h(px(2.)) .overflow_hidden() .bg(theme::border()) .child( div() .absolute() .top_0() .h_full() .w(relative(PROGRESS_BAR_WIDTH)) .bg(theme::own_read()) .with_animation( "sync-progress", Animation::new(PROGRESS_BAR_PERIOD).repeat(), |bar, delta| { let travel = 1. + PROGRESS_BAR_WIDTH; // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0). bar.left(relative( (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH, )) }, ), ) } fn add_people_button(app: &Entity, chat_id: &str) -> AnyElement { let (app, chat_id) = (app.clone(), chat_id.to_owned()); Button::new("chat-add-people") .ghost() .compact() .icon(IconName::UserPlus) .tooltip("Add people") .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx)) .into_any_element() } fn runway(content: impl IntoElement, comfy: bool) -> AnyElement { if comfy { h_flex() .w_full() .justify_center() .child(div().w_full().max_w(px(COMFY_RUNWAY_WIDTH)).child(content)) .into_any_element() } else { content.into_any_element() } } #[cfg(test)] mod tests { use std::sync::Arc; use super::{ DropTarget, HOVER_LEAVE_GRACE, HoverSlot, drop_overlay_text, typing_bottom_offset, }; use gpui_kit::test::TestWindowExt as _; use gpui_kit::{AppContext as _, TestAppContext, WindowOptions}; use store::Store; use super::ConversationView; use crate::app_state::{AppState, Mode, Selection}; #[test] fn chat_overlay_names_the_chat_and_the_onedrive() { assert_eq!( drop_overlay_text("Mara Lin", DropTarget::Chat, 3), ( "Drop to attach to Mara Lin".to_owned(), "3 files. Images go into the message, other files to your OneDrive.".to_owned() ) ); } #[test] fn channel_overlay_points_to_the_channel_files() { let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1); assert_eq!( detail, "1 file. Images go into the message, other files to the channel's Files." ); } #[test] fn new_chat_overlay_says_files_wait_for_the_chat() { let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2); assert_eq!(heading, "Drop to attach to the new chat"); assert_eq!( detail, "2 files. Images go into the message. Files can be added once the chat exists." ); } #[gpui_kit::test] fn the_toolbar_outlives_a_short_leave_and_moves_at_once(cx: &mut TestAppContext) { cx.update(gpui_kit::init); let store = Arc::new(Store::open_in_memory().unwrap()); crate::demo::seed(&store); let view = cx.update(|cx| { let app = cx.new(|_| AppState::new(store, Mode::default())); gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { cx.new(|cx| ConversationView::new(app, window, cx)) }) .unwrap() .1 }); let hover = |cx: &mut TestAppContext, slot: HoverSlot, key: &str, hovered: bool| { cx.update(|cx| view.update(cx, |this, cx| this.set_hover(slot, key, hovered, cx))); }; let shown = |cx: &mut TestAppContext| { cx.update(|cx| { let this = view.read(cx); (this.hovered_message.clone(), this.toolbar_hovered.clone()) }) }; hover(cx, HoverSlot::Row, "a", true); hover(cx, HoverSlot::Row, "a", false); assert_eq!(shown(cx).0.as_deref(), Some("a")); hover(cx, HoverSlot::Toolbar, "a", true); cx.executor().advance_clock(HOVER_LEAVE_GRACE * 2); assert_eq!(shown(cx), (Some("a".into()), Some("a".into()))); hover(cx, HoverSlot::Toolbar, "a", false); cx.executor().advance_clock(HOVER_LEAVE_GRACE * 2); assert_eq!(shown(cx), (None, None)); hover(cx, HoverSlot::Row, "a", true); hover(cx, HoverSlot::Row, "a", false); hover(cx, HoverSlot::Row, "b", true); assert_eq!(shown(cx).0.as_deref(), Some("b")); cx.executor().advance_clock(HOVER_LEAVE_GRACE * 2); assert_eq!(shown(cx).0.as_deref(), Some("b")); hover(cx, HoverSlot::Row, "c", true); hover(cx, HoverSlot::Toolbar, "c", true); hover(cx, HoverSlot::Row, "c", false); cx.executor().advance_clock(HOVER_LEAVE_GRACE * 2); assert_eq!(shown(cx).1.as_deref(), Some("c")); } #[gpui_kit::test] fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) { cx.update(gpui_kit::init); let store = Arc::new(Store::open_in_memory().unwrap()); crate::demo::seed(&store); let mode = Mode { demo: true, read_only: false, demo_sync: None, }; let (handle, app, _view) = cx.update(|cx| { let app = cx.new(|_| { let mut state = AppState::new(store, mode); crate::demo::seed_directory(&mut state); state.selection = Some(crate::demo::first_selection()); state }); let shared = app.clone(); let (handle, view) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { cx.new(|cx| ConversationView::new(shared, window, cx)) }) .unwrap(); (handle, app, view) }); cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx))); let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| { cx.update_window(handle, move |_, window, cx| { run(window, cx); window.render_frame(cx); }) .unwrap(); }; step(cx, |window, cx| window.render_frame(cx)); step(cx, |window, cx| window.input("lea", cx)); step(cx, |window, cx| window.press("enter", cx)); step(cx, |window, cx| window.press("enter", cx)); step(cx, |window, cx| window.input("Hello Lea", cx)); step(cx, |window, cx| window.press("enter", cx)); cx.update(|cx| { let state = app.read(cx); assert!(!state.new_chat); assert_eq!( state.selection, Some(Selection::Chat("demo-chat-new-1".to_owned())) ); let chat = state .sidebar .chats .iter() .find(|chat| chat.id == "demo-chat-new-1") .expect("new chat in the sidebar"); assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea")); }); } #[gpui_kit::test] fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) { cx.update(gpui_kit::init); let store = Arc::new(Store::open_in_memory().unwrap()); crate::demo::seed(&store); let mode = Mode { demo: true, read_only: false, demo_sync: None, }; let (handle, app) = cx.update(|cx| { let app = cx.new(|_| { let mut state = AppState::new(store, mode); crate::demo::seed_directory(&mut state); state.selection = Some(crate::demo::first_selection()); state }); let shared = app.clone(); let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| { cx.new(|cx| ConversationView::new(shared, window, cx)) }) .unwrap(); (handle, app) }); cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx))); cx.update_window(handle, |_, window, cx| { window.render_frame(cx); window.press("escape", cx); window.render_frame(cx); window.press("escape", cx); window.render_frame(cx); }) .unwrap(); cx.update(|cx| { let state = app.read(cx); assert!(!state.new_chat); assert_eq!(state.selection, Some(crate::demo::first_selection())); }); } #[test] fn the_typing_bubble_follows_the_last_row_and_sticks_above_the_composer() { use gpui_kit::{Bounds, point, px, size}; let timeline = Bounds::new(point(px(0.), px(100.)), size(px(800.), px(600.))); let row_ending_at = |bottom: f32| { Some(Bounds::new( point(px(0.), px(bottom - 50.)), size(px(800.), px(50.)), )) }; assert_eq!( typing_bottom_offset(Some(timeline), row_ending_at(400.), 8.), 256. ); assert_eq!( typing_bottom_offset(Some(timeline), row_ending_at(900.), 8.), 8. ); assert_eq!(typing_bottom_offset(Some(timeline), None, 13.), 13.); } #[test] fn no_access_is_a_roster_denial_and_other_errors_still_refresh() { assert!(ConversationView::denies_access(&teams_core::Error::Graph( graph::Error::NotAMember ))); assert!(!ConversationView::denies_access( &teams_core::Error::Unsupported("refresh") )); } }