BlueGit

ict rusty-teams

Files

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

conversation.rs

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