BlueGit

ict rusty-teams

Files

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

conversation.rs

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