BlueGit

ict rusty-teams

Files

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

conversation.rs

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