BlueGit

ict rusty-teams

Files

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

conversation.rs

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