BlueGit

ict rusty-teams

Files

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

conversation.rs

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