BlueGit

ict rusty-teams

Files

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

conversation.rs

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