BlueGit

ict rusty-teams

Files

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

conversation.rs

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