BlueGit

ict rusty-teams

Files

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

conversation.rs

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