BlueGit

ict rusty-teams

Files

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

conversation.rs

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