BlueGit

ict rusty-teams

Files

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

conversation.rs

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