BlueGit

ict rusty-teams

Files

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

conversation.rs

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