BlueGit

ict rusty-teams

Files

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

conversation.rs

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