BlueGit

ict rusty-teams

Files

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

conversation.rs

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