BlueGit

ict rusty-teams

Files

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

conversation.rs

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