BlueGit

ict rusty-teams

Files

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

conversation.rs

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