BlueGit

ict rusty-teams

Files

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

conversation.rs

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