BlueGit

ict rusty-teams

Files

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

conversation.rs

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