BlueGit

ict rusty-teams

Files

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

conversation.rs

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