BlueGit

ict rusty-teams

Files

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

conversation.rs

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