BlueGit

ict rusty-teams

Files

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

conversation.rs

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