BlueGit

ict rusty-teams

Files

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

conversation.rs

conversation.rs 150.7 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 if hovered && matches!(slot, HoverSlot::Row) {
2578 self.request_post_follow(key, cx);
2579 }
2580 let target = match slot {
2581 HoverSlot::Row => &mut self.hovered_message,
2582 HoverSlot::Toolbar => &mut self.toolbar_hovered,
2583 };
2584 if hovered {
2585 *target = Some(key.to_owned());
2586 } else if target.as_deref() == Some(key) {
2587 *target = None;
2588 }
2589 if hovered
2590 && matches!(slot, HoverSlot::Row)
2591 && self.toolbar_hovered.as_deref().is_some_and(|toolbar| toolbar != key)
2592 {
2593 self.toolbar_hovered = None;
2594 }
2595 if let Some(suppressed) = self.toolbar_suppressed.as_deref()
2596 && self.hovered_message.as_deref() != Some(suppressed)
2597 && self.toolbar_hovered.as_deref() != Some(suppressed)
2598 {
2599 self.toolbar_suppressed = None;
2600 }
2601 cx.notify();
2602 }
2603
2604 fn suppress_toolbar(&mut self, key: &str, cx: &mut Context<Self>) {
2605 if self.toolbar_hovered.as_deref() == Some(key) {
2606 self.toolbar_hovered = None;
2607 }
2608 self.toolbar_suppressed = Some(key.to_owned());
2609 cx.notify();
2610 }
2611
2612 fn set_pinned(&mut self, key: &str, open: bool, cx: &mut Context<Self>) {
2613 if open {
2614 self.toolbar_pinned = Some(key.to_owned());
2615 } else if self.toolbar_pinned.as_deref() == Some(key) {
2616 self.toolbar_pinned = None;
2617 }
2618 cx.notify();
2619 }
2620
2621 fn toolbar_visible(&self, key: &str) -> bool {
2622 self.toolbar_suppressed.as_deref() != Some(key)
2623 && self
2624 .toolbar_pinned
2625 .as_deref()
2626 .or(self.toolbar_hovered.as_deref())
2627 .or(self.hovered_message.as_deref())
2628 == Some(key)
2629 }
2630
2631 fn toggle_reaction(&mut self, message_id: &str, glyph: &str, cx: &mut Context<Self>) {
2632 self.change_reaction(message_id, glyph, false, None, cx);
2633 }
2634
2635 fn change_reaction(
2636 &mut self,
2637 message_id: &str,
2638 glyph: &str,
2639 only_add: bool,
2640 accepted_proposal: Option<String>,
2641 cx: &mut Context<Self>,
2642 ) -> ReactionAttempt {
2643 let Some(conversation_id) = self.conversation_id() else {
2644 return ReactionAttempt::Blocked;
2645 };
2646 let state = self.app.read(cx);
2647 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2648 let engine = engine.filter(|_| !mode.read_only);
2649 if !mode.demo && engine.is_none() {
2650 self.show_notice("Read-only mode: reaction not sent", cx);
2651 return ReactionAttempt::Blocked;
2652 }
2653 let my_user_id = self.row_context(cx).my_user_id;
2654 let Some(mut record) = store
2655 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2656 .ok()
2657 .and_then(|mut found| found.remove(message_id))
2658 else {
2659 return ReactionAttempt::MissingMessage;
2660 };
2661 let wanted = reaction_glyph(glyph);
2662 let mut visible = teams_core::reactions(&record);
2663 apply_pending_reactions(
2664 &mut visible,
2665 self.pending_reactions.get(message_id),
2666 my_user_id.as_deref(),
2667 Utc::now(),
2668 );
2669 let added = !has_own_reaction(&visible, glyph, my_user_id.as_deref());
2670 if only_add && !added {
2671 return ReactionAttempt::AlreadyThere;
2672 }
2673 let skin_tone = teams_core::skin_tone(&store);
2674 let wanted = if added {
2675 wanted
2676 } else {
2677 let own = own_reaction_glyph(&visible, glyph, my_user_id.as_deref()).unwrap_or(wanted);
2678 if emoticons::without_tone(&own) == own {
2679 emoticons::with_tone(&own, skin_tone)
2680 } else {
2681 own
2682 }
2683 };
2684 let glyph = wanted.as_str();
2685 let Some(engine) = engine.filter(|_| !mode.demo) else {
2686 let mut reactions = teams_core::reactions(&record);
2687 set_own_reaction(
2688 &mut reactions,
2689 glyph,
2690 my_user_id.as_deref(),
2691 added,
2692 Utc::now(),
2693 );
2694 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2695 let _ = store.upsert_messages(std::slice::from_ref(&record));
2696 if added {
2697 self.record_reaction_use(glyph, cx);
2698 }
2699 self.rebuild(false, cx);
2700 return ReactionAttempt::Acted;
2701 };
2702 let entries = self
2703 .pending_reactions
2704 .entry(message_id.to_owned())
2705 .or_default();
2706 entries.retain(|(pending, _)| {
2707 emoticons::without_tone(pending) != emoticons::without_tone(&wanted)
2708 });
2709 entries.push((wanted.clone(), added));
2710 self.rebuild(false, cx);
2711 let (message_id, glyph) = (message_id.to_owned(), glyph.to_owned());
2712 let reaction_type = api_reaction(&wanted);
2713 let receiver = runtime::spawn({
2714 let (conversation_id, message_id) = (conversation_id.clone(), message_id.clone());
2715 async move {
2716 if added {
2717 engine
2718 .set_reaction(&conversation_id, &message_id, &reaction_type)
2719 .await
2720 } else {
2721 engine
2722 .unset_reaction(&conversation_id, &message_id, &reaction_type)
2723 .await
2724 }
2725 }
2726 });
2727 cx.spawn(async move |this, cx| {
2728 let outcome = match receiver.await {
2729 Ok(Ok(())) => Ok(()),
2730 Ok(Err(error)) => Err(short_error(&error)),
2731 Err(_) => Err("cancelled".to_owned()),
2732 };
2733 this.update(cx, |this, cx| {
2734 this.finish_reaction(
2735 &conversation_id,
2736 &message_id,
2737 &glyph,
2738 added,
2739 accepted_proposal.as_deref(),
2740 outcome,
2741 cx,
2742 )
2743 })
2744 .ok();
2745 })
2746 .detach();
2747 ReactionAttempt::Started
2748 }
2749
2750 fn finish_reaction(
2751 &mut self,
2752 conversation_id: &str,
2753 message_id: &str,
2754 glyph: &str,
2755 added: bool,
2756 accepted_proposal: Option<&str>,
2757 outcome: Result<(), String>,
2758 cx: &mut Context<Self>,
2759 ) {
2760 let wanted = reaction_glyph(glyph);
2761 let store = self.app.read(cx).store.clone();
2762 if let Some(proposal_id) = accepted_proposal.filter(|_| outcome.is_ok()) {
2763 crate::agent_api::resolve_reaction_proposal(
2764 conversation_id,
2765 message_id,
2766 proposal_id,
2767 mcp::ReactionOutcome::Accepted,
2768 cx,
2769 );
2770 }
2771 if outcome.is_ok() {
2772 let my_user_id = self.row_context(cx).my_user_id;
2773 if let Some(mut record) = store
2774 .messages_by_id(conversation_id, &[message_id.to_owned()])
2775 .ok()
2776 .and_then(|mut found| found.remove(message_id))
2777 {
2778 let mut reactions = teams_core::reactions(&record);
2779 set_own_reaction(
2780 &mut reactions,
2781 glyph,
2782 my_user_id.as_deref(),
2783 added,
2784 Utc::now(),
2785 );
2786 record.reactions_json = serde_json::to_string(&reactions).unwrap_or_default();
2787 let _ = store.upsert_messages(std::slice::from_ref(&record));
2788 }
2789 if added {
2790 self.record_reaction_use(glyph, cx);
2791 }
2792 }
2793 if let Some(entries) = self.pending_reactions.get_mut(message_id) {
2794 entries.retain(|entry| *entry != (wanted.clone(), added));
2795 if entries.is_empty() {
2796 self.pending_reactions.remove(message_id);
2797 }
2798 }
2799 self.rebuild(false, cx);
2800 if let Err(error) = outcome {
2801 self.show_notice(&format!("Reaction failed: {error}"), cx);
2802 }
2803 }
2804
2805 fn record_reaction_use(&mut self, glyph: &str, cx: &mut Context<Self>) {
2806 if chatsvc::custom_emoji(glyph).is_some() {
2807 return;
2808 }
2809 let store = self.app.read(cx).store.clone();
2810 self.recent.update(cx, |recent, cx| {
2811 recent.reload(&store);
2812 recent.record_use(&emoticons::without_tone(glyph));
2813 recent.save(&store);
2814 cx.notify();
2815 });
2816 }
2817
2818 fn begin_edit(&mut self, message_id: &str, window: &mut Window, cx: &mut Context<Self>) {
2819 let Some(record) = self.own_record(message_id, cx) else {
2820 return;
2821 };
2822 let edit = EditPreview {
2823 message_id: record.message_id.clone(),
2824 excerpt: reply_excerpt(&record),
2825 scheduled: None,
2826 };
2827 let in_chat = matches!(
2828 self.current.as_ref().map(|current| &current.selection),
2829 Some(Selection::Chat(_))
2830 );
2831 let mentions = if in_chat {
2832 teams_core::user_mention_inputs(&record)
2833 } else {
2834 Vec::new()
2835 };
2836 let draft = Outgoing {
2837 draft: message_draft(&record),
2838 subject: None,
2839 mentions,
2840 reply: None,
2841 edit: Some(edit),
2842 images: Vec::new(),
2843 files: Vec::new(),
2844 link_preview: None,
2845 importance: Default::default(),
2846 };
2847 self.show_main_composer(cx);
2848 self.composer
2849 .update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
2850 }
2851
2852 fn edit_last_own(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2853 if self.draft_active {
2854 return;
2855 }
2856 let key = self
2857 .rows
2858 .borrow()
2859 .iter()
2860 .flat_map(Row::messages)
2861 .filter(|message| {
2862 message.own && !message.deleted && !message.key.starts_with(PENDING_KEY_PREFIX)
2863 })
2864 .max_by_key(|message| message.created_at)
2865 .map(|message| message.key.clone());
2866 if let Some(key) = key {
2867 self.begin_edit(&key, window, cx);
2868 }
2869 }
2870
2871 fn send_edit(&mut self, outgoing: Outgoing, window: &mut Window, cx: &mut Context<Self>) {
2872 let Some(edit) = outgoing.edit.clone() else {
2873 return;
2874 };
2875 let Some(conversation_id) = self.conversation_id() else {
2876 return;
2877 };
2878 let state = self.app.read(cx);
2879 let (mode, engine, store) = (state.mode, state.engine.clone(), state.store.clone());
2880 if mode.demo {
2881 if let Some(mut record) = self.own_record(&edit.message_id, cx) {
2882 record.body_html = outgoing.html();
2883 record.edited_at = Some(Utc::now());
2884 let _ = store.upsert_messages(std::slice::from_ref(&record));
2885 self.rebuild(false, cx);
2886 }
2887 return;
2888 }
2889 let Some(engine) = engine.filter(|_| !mode.read_only) else {
2890 self.notice = Some("Read-only mode: edit not saved".to_owned());
2891 self.show_main_composer(cx);
2892 self.composer
2893 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2894 cx.notify();
2895 return;
2896 };
2897 let sent = outgoing.clone();
2898 let receiver = runtime::spawn(async move {
2899 engine
2900 .edit_message_html(
2901 &conversation_id,
2902 &edit.message_id,
2903 &sent.html(),
2904 &sent.mentions,
2905 )
2906 .await
2907 });
2908 cx.spawn_in(window, async move |this, cx| {
2909 let failed = !matches!(receiver.await, Ok(Ok(())));
2910 this.update_in(cx, |this, window, cx| {
2911 if failed {
2912 this.show_main_composer(cx);
2913 if this.composer.read(cx).is_empty(cx) {
2914 this.notice =
2915 Some("Edit failed: your text is back in the composer".to_owned());
2916 this.composer
2917 .update(cx, |composer, cx| composer.restore(&outgoing, window, cx));
2918 } else {
2919 this.notice = Some("Edit failed".to_owned());
2920 }
2921 cx.notify();
2922 }
2923 })
2924 .ok();
2925 })
2926 .detach();
2927 }
2928
2929 fn copy_text(&self, message_id: &str, cx: &mut Context<Self>) {
2930 let Some(conversation_id) = self.conversation_id() else {
2931 return;
2932 };
2933 let record = self
2934 .app
2935 .read(cx)
2936 .store
2937 .messages_by_id(&conversation_id, &[message_id.to_owned()])
2938 .ok()
2939 .and_then(|mut found| found.remove(message_id));
2940 if let Some(record) = record {
2941 cx.write_to_clipboard(ClipboardItem::new_string(message_text(&record)));
2942 }
2943 }
2944
2945 fn refresh_card(
2946 &mut self,
2947 key: &str,
2948 card_index: usize,
2949 action: ExecuteAction,
2950 cx: &mut Context<Self>,
2951 ) {
2952 let Some(conversation_id) = self.conversation_id() else {
2953 return;
2954 };
2955 let scope = CardScope::message(&conversation_id, key, card_index);
2956 self.app.update(cx, |state, cx| {
2957 state.refresh_card_manually(scope, action, cx)
2958 });
2959 }
2960
2961 pub(super) fn translate_message(&mut self, key: &str, cx: &mut Context<Self>) {
2962 let Some(conversation_id) = self.conversation_id() else {
2963 return;
2964 };
2965 self.app.update(cx, |state, cx| {
2966 state.translate_message(&conversation_id, key, cx)
2967 });
2968 }
2969
2970 fn show_notice(&mut self, message: &str, cx: &mut Context<Self>) {
2971 self.app.update(cx, |state, cx| {
2972 state.raise_notice(message.to_owned(), None, cx)
2973 });
2974 }
2975
2976 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2977 let (Some(conversation_id), Some(runs)) =
2978 (self.conversation_id(), crate::agents::runs_handle(cx))
2979 else {
2980 return (Vec::new(), None);
2981 };
2982 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
2983 return (Vec::new(), None);
2984 }
2985 let settings = runs.read(cx).settings();
2986 let entries: Vec<DelegateEntry> = settings
2987 .actions
2988 .iter()
2989 .map(|action| {
2990 let request = StartRequest {
2991 action_id: action.id.clone(),
2992 conversation_id: conversation_id.clone(),
2993 message_id: key.to_owned(),
2994 };
2995 let agent_name = settings
2996 .agents
2997 .iter()
2998 .find(|agent| agent.id == action.agent_id)
2999 .map(|agent| agent.name.clone())
3000 .unwrap_or_default();
3001 DelegateEntry {
3002 label: action.label.clone(),
3003 agent_name,
3004 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
3005 }
3006 })
3007 .collect();
3008 let manage_agents = (!entries.is_empty()).then(|| {
3009 Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
3010 });
3011 (entries, manage_agents)
3012 }
3013
3014 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
3015 let Some(conversation_id) = self.conversation_id() else {
3016 return (false, HashSet::new());
3017 };
3018 let Some(runs) = crate::agents::runs_handle(cx) else {
3019 return (false, HashSet::new());
3020 };
3021 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
3022 for run in runs.read(cx).for_conversation(&conversation_id) {
3023 snapshot.insert(run.message_id.clone(), run.clone());
3024 }
3025 let layouts: HashMap<String, (usize, bool)> = snapshot
3026 .iter()
3027 .map(|(key, run)| (key.clone(), run.layout_key()))
3028 .collect();
3029 let layout_changed: HashSet<String> = layouts
3030 .iter()
3031 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
3032 .map(|(key, _)| key.clone())
3033 .chain(
3034 self.agent_layouts
3035 .keys()
3036 .filter(|key| !layouts.contains_key(*key))
3037 .cloned(),
3038 )
3039 .collect();
3040 self.agent_layouts = layouts;
3041 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
3042 *self.agent_runs.borrow_mut() = snapshot;
3043 (snapshot_changed, layout_changed)
3044 }
3045
3046 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
3047 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
3048 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
3049 self.remeasure_rows_of(&changed, cx);
3050 if snapshot_changed || any_running {
3051 cx.notify();
3052 }
3053 }
3054
3055 fn remeasure_rows_of(&mut self, keys: &HashSet<String>, cx: &mut Context<Self>) {
3056 if keys.is_empty() {
3057 return;
3058 }
3059 let indices: Vec<usize> = self
3060 .rows
3061 .borrow()
3062 .iter()
3063 .enumerate()
3064 .filter(|(_, row)| row.messages().any(|message| keys.contains(&message.key)))
3065 .map(|(index, _)| index)
3066 .collect();
3067 self.scroller.update(cx, |scroller, cx| {
3068 for index in indices {
3069 scroller.remeasure_items(index..index + 1, cx);
3070 }
3071 });
3072 }
3073
3074 fn message_menu(
3075 &self,
3076 message: &MessageRow,
3077 mine: HashSet<String>,
3078 refresh: Option<(usize, ExecuteAction)>,
3079 view: WeakEntity<Self>,
3080 cx: &App,
3081 ) -> MessageMenu {
3082 let (key, own) = (message.key.as_str(), message.own);
3083 let translate_label = match message.translation {
3084 Some(TranslationLine::Translated {
3085 showing_original: false,
3086 ..
3087 }) => "See original",
3088 Some(TranslationLine::Translated { .. }) => "See translation",
3089 _ => "Translate",
3090 };
3091 let action = |run: fn(&mut Self, &str, &mut Window, &mut Context<Self>)| -> Action {
3092 let (view, key) = (view.clone(), key.to_owned());
3093 Rc::new(move |window, cx| {
3094 view.update(cx, |this, cx| {
3095 this.set_pinned(&key, false, cx);
3096 run(this, &key, window, cx)
3097 })
3098 .ok();
3099 })
3100 };
3101 let react: PickHandler = {
3102 let (view, key) = (view.clone(), key.to_owned());
3103 Rc::new(move |glyph, _, cx| {
3104 view.update(cx, |this, cx| this.toggle_reaction(&key, glyph, cx))
3105 .ok();
3106 })
3107 };
3108 let hover = {
3109 let (view, key) = (view.clone(), key.to_owned());
3110 Rc::new(move |hovered: bool, cx: &mut App| {
3111 view.update(cx, |this, cx| {
3112 this.set_hover(HoverSlot::Toolbar, &key, hovered, cx)
3113 })
3114 .ok();
3115 })
3116 };
3117 let pin = {
3118 let (view, key) = (view.clone(), key.to_owned());
3119 Rc::new(move |open: bool, _: &mut Window, cx: &mut App| {
3120 view.update(cx, |this, cx| this.set_pinned(&key, open, cx))
3121 .ok();
3122 })
3123 };
3124 let refresh_card = refresh.map(|(card_index, refresh_action)| {
3125 let (view, key) = (view.clone(), key.to_owned());
3126 Rc::new(move |_: &mut Window, cx: &mut App| {
3127 view.update(cx, |this, cx| {
3128 this.refresh_card(&key, card_index, refresh_action.clone(), cx)
3129 })
3130 .ok();
3131 }) as Action
3132 });
3133 let chat_id = self.chat_id();
3134 let state = self.app.read(cx);
3135 let saved = self
3136 .conversation_id()
3137 .is_some_and(|conversation_id| state.is_saved(&conversation_id, key));
3138 let quick = state.quick_reactions();
3139 let in_chat = chat_id.is_some();
3140 let pin_conversation_id = self.pin_conversation_id();
3141 let pinned = pin_conversation_id
3142 .as_deref()
3143 .is_some_and(|conversation_id| state.is_pinned(conversation_id, key));
3144 let pinnable = in_chat
3145 || pin_conversation_id.as_deref().is_some_and(|channel_id| {
3146 state
3147 .message_record(channel_id, key)
3148 .is_some_and(|record| record.reply_to_id.is_none())
3149 });
3150 let (delegate, manage_agents) = self.delegate_entries(key, cx);
3151 let post_followed = self.post_follow(key, cx);
3152 MessageMenu {
3153 key: key.to_owned(),
3154 react,
3155 reply: Some(action(|this, key, window, cx| {
3156 this.begin_reply(key, window, cx)
3157 })),
3158 forward: Some(action(|this, key, _, cx| this.forward_message(key, cx))),
3159 forward_multiple: in_chat
3160 .then(|| action(|this, key, _, cx| this.start_forward_selection(key, cx))),
3161 copy_link: Some(action(|this, key, _, cx| this.copy_link(key, cx))),
3162 copy: action(|this, key, _, cx| this.copy_text(key, cx)),
3163 translate: Some(action(|this, key, _, cx| this.translate_message(key, cx))),
3164 translate_label,
3165 share_to_outlook: Some(action(|this, key, _, cx| this.share_to_outlook(key, cx))),
3166 save: Some(action(|this, key, _, cx| this.toggle_saved(key, cx))),
3167 saved,
3168 toggle_pinned: pinnable
3169 .then(|| action(|this, key, window, cx| this.toggle_pinned(key, window, cx))),
3170 pinned,
3171 toggle_follow: post_followed
3172 .map(|_| action(|this, key, _, cx| this.toggle_post_follow(key, cx))),
3173 followed: post_followed.unwrap_or_default(),
3174 edit: own.then(|| action(|this, key, window, cx| this.begin_edit(key, window, cx))),
3175 delete: own.then(|| action(|this, key, _, cx| this.delete(key, cx))),
3176 mark_unread: (in_chat && !own)
3177 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
3178 refresh_card,
3179 delegate,
3180 manage_agents,
3181 pin,
3182 hover,
3183 picker: self.picker.clone(),
3184 quick,
3185 mine,
3186 done: action(|this, key, _, cx| this.suppress_toolbar(key, cx)),
3187 }
3188 }
3189
3190 fn retry(&mut self, key: &str, window: &mut Window, cx: &mut Context<Self>) {
3191 let Some(outgoing) = self.pending_outgoing.remove(key) else {
3192 return;
3193 };
3194 let reply_root = self
3195 .pending
3196 .iter()
3197 .find(|row| row.key == key)
3198 .and_then(|row| row.reply_root.clone());
3199 self.pending.retain(|row| row.key != key);
3200 if self.draft_active {
3201 self.send_new_chat(outgoing, window, cx);
3202 } else {
3203 self.send_as(key.to_owned(), outgoing, reply_root, window, cx);
3204 }
3205 }
3206
3207 fn finish_send(
3208 &mut self,
3209 key: &str,
3210 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
3211 cx: &mut Context<Self>,
3212 ) {
3213 let failure = match result {
3214 Ok(Ok(())) => None,
3215 Ok(Err(error)) => Some(short_error(&error)),
3216 Err(error) => Some(short_error(&error)),
3217 };
3218 let store = self.app.read(cx).store.clone();
3219 match failure {
3220 None => {
3221 store.delete_outbox(key).ok();
3222 self.pending.retain(|row| row.key != key);
3223 self.pending_outgoing.remove(key);
3224 }
3225 Some(error) => {
3226 store.mark_outbox_failed(key, &error).ok();
3227 if let Some(row) = self.pending.iter_mut().find(|row| row.key == key) {
3228 row.delivery = Delivery::Failed(error.clone());
3229 self.notice = Some(format!("Not sent: {error}"));
3230 }
3231 }
3232 }
3233 self.app
3234 .update(cx, |state, cx| state.refresh_local_previews(cx));
3235 self.rebuild(false, cx);
3236 }
3237
3238 fn render_drop_overlay(&self, cx: &mut Context<Self>) -> impl IntoElement {
3239 let target = match self.current.as_ref().map(|current| &current.selection) {
3240 Some(Selection::Chat(_)) => DropTarget::Chat,
3241 Some(Selection::Channel(_)) if self.shared_active() => DropTarget::Library,
3242 Some(Selection::Channel(_)) => DropTarget::Channel,
3243 None => DropTarget::NewChat,
3244 };
3245 let title = self
3246 .current
3247 .as_ref()
3248 .map(|current| current.title.as_str())
3249 .unwrap_or_default();
3250 let (heading, detail) = drop_overlay_text(title, target, self.drag_file_count.max(1));
3251 let composer = self.composer.clone();
3252 div()
3253 .id("drop-overlay")
3254 .absolute()
3255 .top_0()
3256 .left_0()
3257 .size_full()
3258 .opacity(0.)
3259 .bg(theme::drop_background())
3260 .drag_over::<ExternalPaths>(move |style, _, _, cx| {
3261 if composer.read(cx).is_editing() {
3262 style
3263 } else {
3264 style.opacity(1.)
3265 }
3266 })
3267 .on_drag_move(
3268 cx.listener(|this, event: &DragMoveEvent<ExternalPaths>, _, cx| {
3269 let count = event.drag(cx).paths().len();
3270 if this.drag_file_count != count {
3271 this.drag_file_count = count;
3272 cx.notify();
3273 }
3274 }),
3275 )
3276 .on_drop(cx.listener(|this, dropped: &ExternalPaths, window, cx| {
3277 let paths = dropped.paths().to_vec();
3278 if this.shared_active() {
3279 this.upload_paths(paths, cx);
3280 return;
3281 }
3282 this.composer
3283 .update(cx, |composer, cx| composer.add_paths(paths, window, cx));
3284 }))
3285 .child(
3286 div()
3287 .absolute()
3288 .inset(px(12.))
3289 .rounded(px(12.))
3290 .border_2()
3291 .border_color(theme::accent())
3292 .flex()
3293 .items_center()
3294 .justify_center()
3295 .child(
3296 v_flex()
3297 .items_center()
3298 .gap(px(6.))
3299 .px(px(24.))
3300 .py(px(16.))
3301 .rounded(px(12.))
3302 .bg(black().opacity(0.55))
3303 .child(symbol("upload", 28., theme::accent_text()))
3304 .child(
3305 div()
3306 .text_size(px(15.))
3307 .font_weight(FontWeight::SEMIBOLD)
3308 .text_color(theme::text_strong())
3309 .child(heading),
3310 )
3311 .child(
3312 div()
3313 .text_size(px(12.))
3314 .text_color(theme::text_muted())
3315 .child(detail),
3316 ),
3317 ),
3318 )
3319 }
3320
3321 fn render_draft_error(&self, cx: &mut Context<Self>) -> Option<Div> {
3322 let message = self.draft_error.clone()?;
3323 let failed_key = self
3324 .pending
3325 .iter()
3326 .find(|row| matches!(row.delivery, Delivery::Failed(_)))
3327 .map(|row| row.key.clone())?;
3328 Some(
3329 h_flex()
3330 .w_full()
3331 .flex_none()
3332 .px(px(20.))
3333 .py(px(4.))
3334 .gap(px(8.))
3335 .items_center()
3336 .text_size(px(12.))
3337 .text_color(theme::red_soft())
3338 .child(message)
3339 .child(
3340 Button::new("retry-new-chat")
3341 .ghost()
3342 .compact()
3343 .label("Retry")
3344 .on_click(cx.listener(move |this, _, window, cx| {
3345 this.retry(&failed_key, window, cx)
3346 })),
3347 ),
3348 )
3349 }
3350
3351 pub fn open_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3352 if self.pinned || self.draft_active {
3353 return;
3354 }
3355 let Some(selection) = self
3356 .current
3357 .as_ref()
3358 .map(|current| current.selection.clone())
3359 else {
3360 return;
3361 };
3362 self.channel_details_open = false;
3363 if let Some(panel) = &self.find_panel {
3364 panel.update(cx, |panel, cx| panel.focus(window, cx));
3365 return;
3366 }
3367 let app = self.app.clone();
3368 let panel = cx.new(|cx| FindPanel::new(app, selection.clone(), window, cx));
3369 let subscription = cx.subscribe_in(
3370 &panel,
3371 window,
3372 move |this, _, event: &FindPanelEvent, window, cx| match event {
3373 FindPanelEvent::Close => this.close_find(window, cx),
3374 FindPanelEvent::Jump(message_id) => {
3375 let (selection, message_id) = (selection.clone(), message_id.clone());
3376 this.app.update(cx, |state, cx| {
3377 state.jump_to_message(selection, message_id, cx)
3378 });
3379 }
3380 },
3381 );
3382 panel.update(cx, |panel, cx| panel.focus(window, cx));
3383 self.find_panel = Some(panel);
3384 self.find_subscription = Some(subscription);
3385 cx.notify();
3386 }
3387
3388 fn close_find(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3389 self.find_panel = None;
3390 self.find_subscription = None;
3391 self.composer
3392 .update(cx, |composer, cx| composer.focus(window, cx));
3393 cx.notify();
3394 }
3395
3396 fn header_width(&self, window: &Window) -> f32 {
3397 match self.header_width.get() {
3398 width if width > 0. => width,
3399 _ => {
3400 f32::from(window.viewport_size().width)
3401 - RAIL_WIDTH
3402 - SIDEBAR_WIDTH
3403 - 2. * ISLAND_GAP
3404 }
3405 }
3406 }
3407
3408 fn tabs_below_title(&self, window: &Window) -> bool {
3409 self.header_width(window) < TABS_INLINE_MIN_WIDTH
3410 }
3411
3412 fn render_header(
3413 &self,
3414 current: &Current,
3415 tabs: Option<AnyElement>,
3416 cx: &mut Context<Self>,
3417 ) -> impl IntoElement {
3418 let app = self.app.read(cx);
3419 let directory = &app.directory;
3420 let me = directory.me.as_ref();
3421 let mut lead: Option<AnyElement> = None;
3422 let mut subline = String::new();
3423 let mut stack: Option<AnyElement> = None;
3424 let mut rename: Option<AnyElement> = None;
3425 match &current.selection {
3426 Selection::Chat(chat_id) => {
3427 if let Some(chat) = app.sidebar.chats.iter().find(|chat| &chat.id == chat_id) {
3428 let faces = others(chat, me);
3429 let face = |(user_id, name): (Option<String>, String)| Face { user_id, name };
3430 let first = faces.first().cloned().map(face);
3431 if let Some(bot) = one_on_one_bot(chat, me) {
3432 lead = Some(bot_tile(directory, &face(bot), 36.));
3433 } else if is_one_on_one(chat) || faces.len() < 2 {
3434 let name = first
3435 .as_ref()
3436 .map_or(current.title.as_str(), |face| face.name.as_str());
3437 let user_id = first.as_ref().and_then(|face| face.user_id.as_deref());
3438 let avatar = person_avatar(directory, user_id, name, 36.);
3439 let presence = user_id.map(|id| directory.presence_of(id));
3440 let avatar = match presence {
3441 Some(kind) => with_presence(avatar, kind, 36., theme::surface())
3442 .into_any_element(),
3443 None => avatar,
3444 };
3445 lead = Some(
3446 opens_profile(div().id("header-avatar").flex_none(), user_id)
3447 .child(avatar)
3448 .into_any_element(),
3449 );
3450 subline = match (user_id, presence) {
3451 (Some(id), Some(presence)) => {
3452 directory.status_label(id, presence).to_owned()
3453 }
3454 _ => String::new(),
3455 };
3456 if is_one_on_one(chat) && !is_notes_chat(chat_id) {
3457 stack = Some(add_people_button(&self.app, chat_id));
3458 }
3459 } else {
3460 if chat.kind == GROUP_KIND
3461 && me.is_some_and(|me| {
3462 chat.members
3463 .iter()
3464 .any(|member| member.user_id.as_deref() == Some(&me.user_id))
3465 })
3466 {
3467 rename = Some(group_name_button(&self.app, chat_id, &chat.title));
3468 }
3469 let pair = AvatarSpec::Pair(face(faces[0].clone()), face(faces[1].clone()));
3470 lead = Some(spec_avatar(directory, &pair, 36., theme::surface()));
3471 subline = format!("{} participants", chat.members.len());
3472 let shown: Vec<Face> = faces.iter().cloned().map(face).collect();
3473 stack = Some(members_popover(
3474 &self.app,
3475 chat_id,
3476 member_stack(directory, &shown, shown.len(), false)
3477 .debug_selector(|| MEMBERS_BUTTON.into()),
3478 ));
3479 }
3480 }
3481 }
3482 Selection::Channel(channel_id) => {
3483 let team = app.sidebar.teams.iter().find(|entry| {
3484 entry
3485 .channels
3486 .iter()
3487 .any(|channel| &channel.id == channel_id)
3488 });
3489 let (name, key) = team
3490 .map_or((current.title.as_str(), current.title.as_str()), |entry| {
3491 (entry.team.name.as_str(), entry.team.id.as_str())
3492 });
3493 lead = Some(square_avatar(name, key, 36., 9.).into_any_element());
3494 }
3495 }
3496 let mut header = h_flex()
3497 .w_full()
3498 .h(px(HEADER_HEIGHT))
3499 .flex_none()
3500 .px(px(HEADER_PADDING))
3501 .gap(px(HEADER_GAP))
3502 .items_center();
3503 if matches!(current.mode, ViewMode::Thread(_)) {
3504 header = header.child(
3505 h_flex()
3506 .id("back-to-channel")
3507 .flex_none()
3508 .gap(px(2.))
3509 .pl(px(4.))
3510 .pr(px(8.))
3511 .py(px(4.))
3512 .items_center()
3513 .rounded(px(6.))
3514 .cursor_pointer()
3515 .text_size(px(13.))
3516 .font_weight(FontWeight::SEMIBOLD)
3517 .text_color(theme::accent_text())
3518 .hover(|button| button.bg(theme::row_hover()))
3519 .on_click(cx.listener(|this, _, _, cx| this.back_to_threads(cx)))
3520 .child(icon(IconName::ChevronLeft, 16., theme::accent_text()))
3521 .child("Back to channel"),
3522 );
3523 }
3524 let channel_note = match current.mode {
3525 ViewMode::Flat => None,
3526 ViewMode::ThreadList => Some("Posts"),
3527 ViewMode::Thread(_) => Some("Conversation"),
3528 };
3529 if let Some(note) = channel_note {
3530 subline = note.to_owned();
3531 }
3532 let call_controls = if self.pinned && !self.popped_out {
3533 Vec::new()
3534 } else {
3535 header_call_controls(&self.app, app, &current.selection)
3536 };
3537 let sync = &current.sync;
3538 let loading_window = current.window_request.is_some();
3539 if sync.failed {
3540 subline = "Not up to date".to_owned();
3541 } else if loading_window {
3542 subline = "Loading message ...".to_owned();
3543 } else if sync.shown_at.is_some() {
3544 subline = if sync.slow {
3545 "Taking longer than usual ..."
3546 } else if sync.empty_cache {
3547 "Loading messages ..."
3548 } else {
3549 "Updating ..."
3550 }
3551 .to_owned();
3552 }
3553 let inline_tabs = tabs.map(|tabs| h_flex().h_full().flex_1().child(tabs));
3554 header
3555 .relative()
3556 .child(record_width(&self.header_width))
3557 .when(sync.shown_at.is_some() || loading_window, |header| {
3558 header.child(progress_bar())
3559 })
3560 .children(lead)
3561 .child(
3562 v_flex()
3563 .map(|column| match inline_tabs {
3564 Some(_) => column.flex_shrink(1.).max_w(px(HEADER_TITLE_MAX_WIDTH)),
3565 None => column.flex_1(),
3566 })
3567 .min_w_0()
3568 .overflow_hidden()
3569 .gap(px(1.))
3570 .child(
3571 h_flex()
3572 .min_w_0()
3573 .gap(px(2.))
3574 .items_center()
3575 .child(
3576 div()
3577 .truncate()
3578 .text_size(px(15.))
3579 .font_weight(FontWeight::SEMIBOLD)
3580 .text_color(theme::text())
3581 .child(current.title.clone()),
3582 )
3583 .children(rename),
3584 )
3585 .when(!subline.is_empty(), |column| {
3586 column.child(
3587 div()
3588 .text_size(px(12.))
3589 .text_color(theme::text_muted())
3590 .child(subline),
3591 )
3592 }),
3593 )
3594 .children(inline_tabs)
3595 .children(stack)
3596 .children(call_controls)
3597 .children(self.channel_details_button(cx))
3598 .children(self.pop_in_button(current))
3599 }
3600
3601 fn pop_in_button(&self, current: &Current) -> Option<AnyElement> {
3602 let Selection::Chat(chat_id) = &current.selection else {
3603 return None;
3604 };
3605 if !self.popped_out {
3606 return None;
3607 }
3608 let (app, chat_id) = (self.app.clone(), chat_id.clone());
3609 Some(
3610 Button::new("chat-pop-in")
3611 .icon(IconName::SquareArrowDownLeft)
3612 .ghost()
3613 .size(px(POP_IN_BUTTON_SIZE))
3614 .rounded(px(8.))
3615 .tooltip(chat_pop_out::POP_IN_TOOLTIP)
3616 .on_click(move |_, window, cx| {
3617 chat_pop_out::return_to_main_window(&app, &chat_id, window, cx)
3618 })
3619 .into_any_element(),
3620 )
3621 }
3622}
3623
3624const GROUP_KIND: &str = "group";
3625
3626impl Render for ConversationView {
3627 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3628 let background = theme::surface();
3629 let mut root = v_flex()
3630 .when(!self.pinned, |root| {
3631 root.debug_selector(|| "shell/islands/main".into())
3632 })
3633 .flex_1()
3634 .w_full()
3635 .min_w_0()
3636 .h_full()
3637 .rounded(px(10.))
3638 .bg(background)
3639 .track_focus(&self.focus_handle);
3640 let drafting = self.draft_active;
3641 if self.current.is_none() && !drafting {
3642 return root
3643 .items_center()
3644 .justify_center()
3645 .text_color(theme::text_muted())
3646 .child("Select a chat or channel")
3647 .into_any_element();
3648 }
3649 let in_feed = self.in_feed();
3650 let detached = self.is_detached();
3651 let rows_seen = self.feed_rows_seen.replace(usize::MAX);
3652 if in_feed && rows_seen != usize::MAX {
3653 self.feed_at_top = rows_seen == 0;
3654 }
3655 let forward_selection = self.active_forward_selection(cx);
3656 let rows = self.rows.clone();
3657 let rows_seen = self.feed_rows_seen.clone();
3658 let env = RenderEnv {
3659 view: cx.weak_entity(),
3660 app: self.app.clone(),
3661 highlighted: self.highlighted_message.clone(),
3662 drafting,
3663 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3664 timeline: self.timeline_bounds.clone(),
3665 agent_runs: self.agent_runs.clone(),
3666 reaction_proposals: self.reaction_proposals.clone(),
3667 forward_selection: forward_selection.clone(),
3668 };
3669 let pin_banner = self
3670 .render_pin_banner(cx)
3671 .filter(|_| !drafting && !self.shared_active() && !self.recap_active());
3672 let timeline_top_inset = pin_banner_inset(pin_banner.is_some());
3673 let scroller = MessageScroller::new(
3674 "messages",
3675 self.scroller.clone(),
3676 move |index, window, cx| {
3677 rows_seen.set(rows_seen.get().min(index));
3678 let rows = rows.borrow();
3679 match rows.get(index) {
3680 Some(Row::Message(message)) => {
3681 let actions = env.message_actions(message, window, cx);
3682 let state = env.app.read(cx);
3683 render_message_row(message, index, actions, &state.directory, cx)
3684 }
3685 Some(Row::Post(post)) => {
3686 let actions = env.post_actions(post, window, cx);
3687 let state = env.app.read(cx);
3688 render_post(post, index, actions, &state.directory, cx)
3689 }
3690 Some(Row::Skeleton(skeleton)) => render_skeleton_row(skeleton, index),
3691 Some(Row::LoadOlder) => {
3692 let view = env.view.clone();
3693 cx.defer(move |cx| {
3694 view.update(cx, |this, cx| this.request_older(cx)).ok();
3695 });
3696 h_flex()
3697 .w_full()
3698 .py_2()
3699 .gap(px(6.))
3700 .justify_center()
3701 .text_size(px(12.))
3702 .text_color(theme::text_muted())
3703 .child(icon(IconName::Loader, 12., theme::text_muted()))
3704 .child("Loading older messages")
3705 .into_any_element()
3706 }
3707 Some(Row::LoadNewer) => {
3708 let view = env.view.clone();
3709 cx.defer(move |cx| {
3710 view.update(cx, |this, cx| {
3711 this.request_window_page(WindowDirection::Forward, cx)
3712 })
3713 .ok();
3714 });
3715 h_flex()
3716 .w_full()
3717 .py_2()
3718 .gap(px(6.))
3719 .justify_center()
3720 .text_size(px(12.))
3721 .text_color(theme::text_muted())
3722 .child(icon(IconName::Loader, 12., theme::text_muted()))
3723 .child("Loading newer messages")
3724 .into_any_element()
3725 }
3726 Some(Row::Start(start)) => {
3727 let state = env.app.read(cx);
3728 v_flex()
3729 .w_full()
3730 .items_center()
3731 .gap(px(8.))
3732 .pt(px(32.))
3733 .pb(px(16.))
3734 .child(match start.user_id.as_deref() {
3735 Some(user_id) if is_bot_id(user_id) => bot_tile(
3736 &state.directory,
3737 &Face {
3738 user_id: Some(user_id.to_owned()),
3739 name: start.title.clone(),
3740 },
3741 56.,
3742 ),
3743 user_id => person_avatar(
3744 &state.directory,
3745 user_id,
3746 &start.avatar_name,
3747 56.,
3748 ),
3749 })
3750 .child(
3751 div()
3752 .text_size(px(16.))
3753 .font_weight(FontWeight::SEMIBOLD)
3754 .text_color(theme::text())
3755 .child(start.title.clone()),
3756 )
3757 .child(
3758 div()
3759 .text_size(px(12.))
3760 .text_color(theme::text_muted())
3761 .child("This is the beginning of the conversation"),
3762 )
3763 .into_any_element()
3764 }
3765 None => div().into_any_element(),
3766 }
3767 },
3768 )
3769 .with_row_style(StyleRefinement::default().px(px(0.)).pb(px(0.)))
3770 .jump_button(!in_feed)
3771 .force_jump_button(detached)
3772 .with_jump_button_label(jump::JUMP_TO_NEWEST_LABEL)
3773 .with_jump_button_renderer(|button| {
3774 button
3775 .label(jump::JUMP_TO_NEWEST_LABEL)
3776 .tooltip(jump::jump_to_newest_tooltip())
3777 .border_0()
3778 .bg(theme::accent())
3779 .text_color(theme::on_accent())
3780 })
3781 .when(detached, |scroller| {
3782 let view = cx.weak_entity();
3783 scroller.on_jump(move |_, cx| {
3784 view.update(cx, |this, cx| this.leave_detached(cx)).ok();
3785 })
3786 })
3787 .with_bottom_fade(background)
3788 .with_top_inset(timeline_top_inset);
3789
3790 root = match self.current.as_ref().filter(|_| !drafting) {
3791 Some(current) => {
3792 let tab_bar = self
3793 .render_tab_bar(window, cx)
3794 .or_else(|| self.render_meeting_tab_bar(cx));
3795 let (inline_tabs, tabs_row) = match tab_bar {
3796 Some(tabs) if self.tabs_below_title(window) => (None, Some(tabs)),
3797 tabs => (tabs, None),
3798 };
3799 root.child(self.render_header(current, inline_tabs, cx))
3800 .children(tabs_row.map(|tabs| {
3801 h_flex()
3802 .w_full()
3803 .h(px(TABS_ROW_HEIGHT))
3804 .flex_none()
3805 .px(px(HEADER_PADDING))
3806 .child(tabs)
3807 }))
3808 .child(edge_divider(HEADER_DIVIDER))
3809 }
3810 None => root.child(self.draft.clone()),
3811 };
3812 let sync_failed = self
3813 .current
3814 .as_ref()
3815 .is_some_and(|current| current.sync.failed);
3816 if let Some(notice) = &self.notice {
3817 root = root.child(
3818 h_flex()
3819 .px(px(20.))
3820 .py_1()
3821 .gap(px(8.))
3822 .items_center()
3823 .text_xs()
3824 .bg(theme::amber().opacity(0.15))
3825 .text_color(theme::amber())
3826 .child(div().flex_1().min_w_0().child(notice.clone()))
3827 .when(sync_failed, |bar| {
3828 bar.child(
3829 Button::new("retry-fetch")
3830 .ghost()
3831 .compact()
3832 .label("Retry")
3833 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
3834 )
3835 }),
3836 );
3837 }
3838 let recap_active = self.recap_active();
3839 let empty_channel = in_feed && self.rows.borrow().is_empty();
3840 let new_post = self.render_new_post(window, cx);
3841 self.watch_feed_scroll(cx);
3842 let feed_scrolled = new_post.is_some() && self.scroller.read(cx).is_scrolled_from_top();
3843 let body = if drafting && self.current.is_none() && self.rows.borrow().is_empty() {
3844 let draft = self.draft.read(cx);
3845 let group_name = draft.group_name(cx);
3846 draft.render_empty(&self.app.read(cx).directory, &group_name)
3847 } else if self.shared_active() {
3848 self.render_shared(cx)
3849 } else if self.recap_active() {
3850 self.render_recap(cx)
3851 } else if let Some(start) = self.notes_space() {
3852 notes_space::render_notes_space(&self.app.read(cx).directory, &start)
3853 } else if empty_channel {
3854 div()
3855 .size_full()
3856 .flex()
3857 .items_center()
3858 .justify_center()
3859 .text_size(px(13.))
3860 .text_color(theme::text_muted())
3861 .child("No posts in this channel yet")
3862 .into_any_element()
3863 } else {
3864 scroller.into_any_element()
3865 };
3866 let channel_details = self.render_channel_details(cx);
3867 let find_panel = self.find_panel.clone().filter(|_| !drafting);
3868 let find_overlays = self.header_width(window) < FIND_PANEL_WIDTH + FIND_MIN_TIMELINE_WIDTH;
3869 let content = v_flex()
3870 .relative()
3871 .flex_1()
3872 .min_w_0()
3873 .min_h_0()
3874 .children(new_post)
3875 .child(
3876 div()
3877 .debug_selector(|| TIMELINE_TAG.into())
3878 .relative()
3879 .flex_1()
3880 .min_h_0()
3881 .child(record_bounds(&self.timeline_bounds, timeline_top_inset))
3882 .on_scroll_wheel(cx.listener(|this, _, _, cx| this.close_reaction_details(cx)))
3883 .child(body)
3884 .when(feed_scrolled, |timeline| {
3885 timeline.child(
3886 edge_divider(FEED_EDGE_TAG)
3887 .absolute()
3888 .top_0()
3889 .left_0()
3890 .right_0(),
3891 )
3892 })
3893 .children(pin_banner.map(pin_banner_overlay)),
3894 )
3895 .children(self.render_draft_error(cx))
3896 .when(
3897 !in_feed && !recap_active,
3898 |column| match &forward_selection {
3899 Some(snapshot) => column.child(self.render_forward_footer(snapshot, cx)),
3900 None => column
3901 .child(self.render_typing_line(cx))
3902 .children(self.render_proposal_card(cx))
3903 .child(self.composer.clone()),
3904 },
3905 )
3906 .child(self.render_drop_overlay(cx));
3907 root.child(
3908 h_flex()
3909 .relative()
3910 .flex_1()
3911 .min_h_0()
3912 .w_full()
3913 .items_stretch()
3914 .child(content)
3915 .children(channel_details)
3916 .children(find_panel.map(|panel| {
3917 div()
3918 .h_full()
3919 .w(px(FIND_PANEL_WIDTH))
3920 .min_w_0()
3921 .flex_shrink(1.)
3922 .when(find_overlays, |slot| {
3923 slot.absolute().top_0().right_0().bottom_0().max_w_full()
3924 })
3925 .child(panel)
3926 })),
3927 )
3928 .capture_action(cx.listener(|this, _: &Escape, _, cx| {
3929 if this.reaction_details.is_some() {
3930 this.close_reaction_details(cx);
3931 cx.stop_propagation();
3932 }
3933 }))
3934 .on_action(cx.listener(|this, _: &Escape, window, cx| {
3935 if this.draft_active {
3936 if this.draft.read(cx).has_focus(window, cx) {
3937 this.draft.update(cx, |draft, cx| draft.escape(cx));
3938 }
3939 } else if this.cancel_forward_selection(cx) {
3940 } else if !this.on_escape(window, cx) {
3941 cx.propagate();
3942 }
3943 }))
3944 .into_any_element()
3945 }
3946}
3947
3948fn typing_dots() -> impl IntoElement {
3949 h_flex()
3950 .gap(px(3.))
3951 .flex_none()
3952 .children((0..TYPING_DOT_COUNT).map(|index| {
3953 let phase_offset = index as f32 / TYPING_DOT_COUNT as f32;
3954 div()
3955 .size(px(TYPING_DOT_SIZE))
3956 .rounded_full()
3957 .bg(theme::text_muted())
3958 .with_animation(
3959 ElementId::NamedInteger("typing-dot".into(), index as u64),
3960 Animation::new(TYPING_PULSE_PERIOD).repeat(),
3961 move |dot, delta| {
3962 let wave = 1. - ((delta - phase_offset).rem_euclid(1.) * 2. - 1.).abs();
3963 dot.opacity(0.3 + 0.7 * wave)
3964 },
3965 )
3966 }))
3967}
3968
3969fn record_width(width: &Rc<Cell<f32>>) -> impl IntoElement {
3970 let width = width.clone();
3971 canvas(
3972 move |bounds, window, _| {
3973 let measured = f32::from(bounds.size.width);
3974 if (measured - width.replace(measured)).abs() > 0.5 {
3975 window.request_animation_frame();
3976 }
3977 },
3978 |_, _, _, _| {},
3979 )
3980 .absolute()
3981 .top_0()
3982 .left_0()
3983 .size_full()
3984}
3985
3986fn progress_bar() -> impl IntoElement {
3987 div()
3988 .absolute()
3989 .left_0()
3990 .right_0()
3991 .bottom(px(-1.))
3992 .h(px(2.))
3993 .overflow_hidden()
3994 .bg(theme::border())
3995 .child(
3996 div()
3997 .absolute()
3998 .top_0()
3999 .h_full()
4000 .w(relative(PROGRESS_BAR_WIDTH))
4001 .bg(theme::own_read())
4002 .with_animation(
4003 "sync-progress",
4004 Animation::new(PROGRESS_BAR_PERIOD).repeat(),
4005 |bar, delta| {
4006 let travel = 1. + PROGRESS_BAR_WIDTH;
4007 // The 0.3 phase keeps the bar on screen in the static reduce-motion frame (delta 0).
4008 bar.left(relative(
4009 (delta + 0.3).fract() * travel - PROGRESS_BAR_WIDTH,
4010 ))
4011 },
4012 ),
4013 )
4014}
4015
4016fn add_people_button(app: &Entity<AppState>, chat_id: &str) -> AnyElement {
4017 let (app, chat_id) = (app.clone(), chat_id.to_owned());
4018 Button::new("chat-add-people")
4019 .ghost()
4020 .compact()
4021 .icon(IconName::UserPlus)
4022 .tooltip("Add people")
4023 .on_click(move |_, window, cx| open_add_people(&app, &chat_id, true, window, cx))
4024 .into_any_element()
4025}
4026
4027#[cfg(test)]
4028mod tests {
4029 use std::sync::Arc;
4030
4031 use super::{DropTarget, drop_overlay_text};
4032
4033 use gpui_kit::test::TestWindowExt as _;
4034 use gpui_kit::{AppContext as _, TestAppContext, WindowOptions};
4035 use store::Store;
4036
4037 use super::ConversationView;
4038 use crate::app_state::{AppState, Mode, Selection};
4039
4040 #[test]
4041 fn chat_overlay_names_the_chat_and_the_onedrive() {
4042 assert_eq!(
4043 drop_overlay_text("Mara Lin", DropTarget::Chat, 3),
4044 (
4045 "Drop to attach to Mara Lin".to_owned(),
4046 "3 files. Images go into the message, other files to your OneDrive.".to_owned()
4047 )
4048 );
4049 }
4050
4051 #[test]
4052 fn channel_overlay_points_to_the_channel_files() {
4053 let (_, detail) = drop_overlay_text("Squad / General", DropTarget::Channel, 1);
4054 assert_eq!(
4055 detail,
4056 "1 file. Images go into the message, other files to the channel's Files."
4057 );
4058 }
4059
4060 #[test]
4061 fn new_chat_overlay_says_files_wait_for_the_chat() {
4062 let (heading, detail) = drop_overlay_text("", DropTarget::NewChat, 2);
4063 assert_eq!(heading, "Drop to attach to the new chat");
4064 assert_eq!(
4065 detail,
4066 "2 files. Images go into the message. Files can be added once the chat exists."
4067 );
4068 }
4069
4070 #[gpui_kit::test]
4071 fn demo_draft_creates_a_chat_and_selects_it(cx: &mut TestAppContext) {
4072 cx.update(gpui_kit::init);
4073 let store = Arc::new(Store::open_in_memory().unwrap());
4074 crate::demo::seed(&store);
4075 let mode = Mode {
4076 demo: true,
4077 read_only: false,
4078 demo_sync: None,
4079 };
4080 let (handle, app, _view) = cx.update(|cx| {
4081 let app = cx.new(|_| {
4082 let mut state = AppState::new(store, mode);
4083 crate::demo::seed_directory(&mut state);
4084 state.selection = Some(crate::demo::first_selection());
4085 state
4086 });
4087 let shared = app.clone();
4088 let (handle, view) =
4089 gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4090 cx.new(|cx| ConversationView::new(shared, window, cx))
4091 })
4092 .unwrap();
4093 (handle, app, view)
4094 });
4095 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4096 let step = |cx: &mut TestAppContext, run: fn(&mut gpui_kit::Window, &mut gpui_kit::App)| {
4097 cx.update_window(handle, move |_, window, cx| {
4098 run(window, cx);
4099 window.render_frame(cx);
4100 })
4101 .unwrap();
4102 };
4103 step(cx, |window, cx| window.render_frame(cx));
4104 step(cx, |window, cx| window.input("lea", cx));
4105 step(cx, |window, cx| window.press("enter", cx));
4106 step(cx, |window, cx| window.press("enter", cx));
4107 step(cx, |window, cx| window.input("Hello Lea", cx));
4108 step(cx, |window, cx| window.press("enter", cx));
4109 cx.update(|cx| {
4110 let state = app.read(cx);
4111 assert!(!state.new_chat);
4112 assert_eq!(
4113 state.selection,
4114 Some(Selection::Chat("demo-chat-new-1".to_owned()))
4115 );
4116 let chat = state
4117 .sidebar
4118 .chats
4119 .iter()
4120 .find(|chat| chat.id == "demo-chat-new-1")
4121 .expect("new chat in the sidebar");
4122 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello Lea"));
4123 });
4124 }
4125
4126 #[gpui_kit::test]
4127 fn escape_closes_the_draft_and_keeps_the_selection(cx: &mut TestAppContext) {
4128 cx.update(gpui_kit::init);
4129 let store = Arc::new(Store::open_in_memory().unwrap());
4130 crate::demo::seed(&store);
4131 let mode = Mode {
4132 demo: true,
4133 read_only: false,
4134 demo_sync: None,
4135 };
4136 let (handle, app) = cx.update(|cx| {
4137 let app = cx.new(|_| {
4138 let mut state = AppState::new(store, mode);
4139 crate::demo::seed_directory(&mut state);
4140 state.selection = Some(crate::demo::first_selection());
4141 state
4142 });
4143 let shared = app.clone();
4144 let (handle, _) = gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
4145 cx.new(|cx| ConversationView::new(shared, window, cx))
4146 })
4147 .unwrap();
4148 (handle, app)
4149 });
4150 cx.update(|cx| app.update(cx, |state, cx| state.start_new_chat(cx)));
4151 cx.update_window(handle, |_, window, cx| {
4152 window.render_frame(cx);
4153 window.press("escape", cx);
4154 window.render_frame(cx);
4155 window.press("escape", cx);
4156 window.render_frame(cx);
4157 })
4158 .unwrap();
4159 cx.update(|cx| {
4160 let state = app.read(cx);
4161 assert!(!state.new_chat);
4162 assert_eq!(state.selection, Some(crate::demo::first_selection()));
4163 });
4164 }
4165}