BlueGit

ict rusty-teams

Files

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

conversation.rs

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